Express js Redirect not rendering page

时间:2017-12-10 14:04:12

标签: express redirect

我试图在登录帐户后重定向使用我网站的用户,他将被重定向到仪表板。
问题是我可以在浏览器检查工具的“网络”选项卡中看到/dashboard路由的请求,但页面从不加载。
到目前为止这是我的代码。

router.post('/login', function(request, response){
    // verify against database and send back response
    var userData = {};
    userData.email = request.body.email;
    userData.password = request.body.password;
    userData.rememberPassword = request.body.rememberPassword;

    // check if in the database and re-route
    var query = database.query('SELECT * FROM users WHERE email = ?', [userData.email], function(error, result){
        if(error){
            console.log('Error ', error);
        }
        if(result.length){
            // check if the password is correct
            if(userData.password === result[0].password){
                // redirect to the dashboard
                // TODO this piece of code does not redirect correctly
                response.redirect('/dashboard'); // < HERE
                console.log('Haha');
            }
        }
        else{
            // do something when there is are no results
            // invalid email status code
            response.statusCode = 405;
            response.send('');
        }
    });
});

这是通往dashboard的路线,并且在浏览器中访问时正确呈现。

router.get('/dashboard', function(request, response){
    response.render(path.resolve(__dirname, 'views', 'dashboard.pug'));
}); 

为什么用户完成登录过程后无法重定向? 感谢。

1 个答案:

答案 0 :(得分:0)

问题可能出在前端,而不是后端。如果您使用AJAX发送 POST 请求,则专门设计为不更改您的网址。

在AJAX的请求完成后使用window.location.href更新带有所需路径的网址。但最简单的方法是创建一个操作为/login的表单并使用提交到触发网址更改。

要确保问题不在于后端,

  1. router.get('/dashboard'添加日志记录语句以验证是否 控制权已通过。
  2. 检查/ login路由的HTTP状态代码是否为302,表示重定向,并且位置标头包含路由/仪表板。
  3. 响应/信息中心的内容类型为text / html。如果不是,请使用res.setHeader("Content-Type", "text/html")进行设置。