1

以下演示项目在这里和博客文章在这里

他使用jade engine的是我don't want使用的,而不是使用 Angularjs 模板和路由。

根文件夹是

client > js (contain all js files)
       > views > partials > html files
       > index.html

在他的代码更改后,我被下面的代码卡住了

我无法发送正确的回复。

如果我res.render('index.html', {layout : null});在刷新页面时使用比得到错误

错误 :

Error: Cannot find module 'html'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)

如果我使用res.redirect('/')比刷新页面总是向我发送 app.js 中定义的根 (/)。

需要:即使我刷新浏览器,我也想发送响应或不在同一页面上。

{
        path: '/*',
        httpMethod: 'GET',
        middleware: [function(req, res) {
           var role = userRoles.public, username = '';
        if(req.user) {
            role = req.user.role;
            username = req.user.username;
        }
        res.cookie('user', JSON.stringify({
            'username': username,
            'role': role
        }));
            //res.render('index.html', {layout : null});
            //res.redirect('/');

        }],
        accessLevel: accessLevels.public
    }
4

1 回答 1

2

如果您不使用后端模板语言(如jade),那么您想使用res.sendfile而不是res.render。Render 将寻找与文件扩展名(例如 .jade)匹配的模板引擎,然后通过它运行文件。在这种情况下,它假定必须有一个名为 html 的渲染引擎,但实际上并没有。SendFile 将简单地传输带有适当标题的文件。

编辑:

我仍然不能 100% 确定你在问什么,但我认为你的意思是如果他们没有登录,你希望你的通配符路由将他们重定向到主页,但如果他们是,那么让其他人路线接管。

如果是这种情况,您只需要检查/*路由的“中间件”功能。

代替:

function(req, res) {
    res.redirect('/');
}

使用某种类型的条件逻辑:

function (req, res, next) {
    if (/* !req.cookie.something or whatever */)
        res.redirect('/');
    else
        next(); // continue on to the next applicable (matching) route handler
}

这样你就不会总是陷入重定向循环。显然,如果需要,上述条件逻辑可以是异步的。

res.sendfile正如 github 成员所建议的那样,我仍然相信这是对您问题另一部分的正确答案。

于 2013-06-08T02:58:32.140 回答