node.js res.redirect 从 POST

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11570301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:03:12  来源:igfitidea点击:

res.redirect from POST

node.jspostexpress

提问by lostAstronaut

For some reason I cant redirect to /blog once my login is completed. In my login controller I have the following.

出于某种原因,我无法在登录完成后重定向到 /blog。在我的登录控制器中,我有以下内容。

module.exports = {

    post: function(req, res) {
         var login = req.body['login'];                      

         if (login && req.body['login']['password'] == "password") {
            console.log('Granted access');
            res.send({redirect: '/blog'});

         }

         else {
             console.log('wrong password');
             res.redirect('back');

         }

    }

};

The jquery ajax

jquery ajax

$(document).ready ->

    $('#login-button').click () ->

        $.ajax
            url: '/login'
            type: 'POST'
            data: $('#Password').serialize()
            dataType: 'json'
            success: (data, textStatus, jqXHR) ->
                if typeof data.redirect == 'string'
                    window.location = data.redirect

updated to working code

更新到工作代码

回答by Charles

You can't make a redirection after an AJAX. You need to do it yourself in Javascript.

您不能在 AJAX 之后进行重定向。您需要在 Javascript 中自己完成。

server

服务器

post: function(req, res) {
     var login = req.body['login'];          
     app.use(express.bodyParser());


     if (login && req.body['login']['password'] == "tom") {
        var loginPassword = req.body['login']['password'];
        console.log(loginPassword);
        console.log('Granted access');
        res.send({redirect: '/blog'});

     }

     ...

}

client

客户

$(document).ready ->
    $('#login-button').click () ->
        $.ajax
            url: '/login'
            type: 'POST'
            data: $('#Password').serialize()
            dataType: 'json'
            success: (data, textStatus, jqXHR) ->
                if typeof data.redirect == 'string'
                    window.location = data.redirect

This should work.

这应该有效。

回答by cjohn

POSTs are redirected to GETs. You can't redirect to a POST to a POST; you could forward it but that would be weird. I recommend adding logic to your GET route that will handle a logged in versus not logged in user.

POST 被重定向到 GET。您不能重定向到 POST 到 POST;你可以转发它,但这会很奇怪。我建议向您的 GET 路由添加逻辑,以处理登录用户和未登录用户。

Also, 304 likely means your response is being cached by your browser because you used a 301 (permanent redirect, very bad on login, etc.; use 302).

此外,304 可能意味着您的响应正在被您的浏览器缓存,因为您使用了 301(永久重定向、登录时非常糟糕等;使用 302)。

回答by Evin Weissenberg

You are missing return:

你失踪了return

return res.redirect('/');