为什么即使一切都正确执行了 POST returns 错误?

Why POST returns error even if everything is executed correctly?

在服务器端有以下代码接收POST请求:

router.post('/signup', function(req, res, next) {
    //console.log(res);
    passport.authenticate('signup', function(err, user, info) {
        console.log(user);
        if (err) {
            console.log(err);
            return next(err);
        }
        if (!user) { return res.json({redirect: 'auth'}); }
        req.logIn(user, function(err) {
            if (err)
            {
                console.log(err);
                return next(err);
            }
            console.log(res);
            return res.json({redirect: 'userPanel'});
        });
    })(req, res, next);
});

在客户端,以下函数执行 POST 请求并处理响应:

$("#btn-signup").click(function() {
    var data = $('form#signupform').serialize();
    $.ajax({
        type: "POST",
        dataType: "jsonp",
        url: "/auth/signup", //process to mail
        data: data,
        success: function(msg) {
            console.log("Received data: " + msg);
            if (msg.redirect) {
                window.location.href = msg.redirect;
            }
        },
        error: function(e) {
            console.log("Error: " + e.responseText);
        }
    });
});

发出 post 请求时,我得到以下控制台输出:

Error: {"redirect":"auth"}

因此我假设服务器 returns 一切正确,但不知道为什么在客户端它被认为是错误。

有谁知道出了什么问题吗?

我猜您遇到了解析错误。 jQuery 期望看到 JSONP,它是 JSON 包装在回调函数中,类似于

callback({"key" : "value"});

但您只返回常规 JSON,如

{"key" : "value"}

将 jQuery 的数据类型从 jsonp 更改为 json

无法使用 JSONP 执行 POST 操作(仅限 GET 操作)。我假设你甚至不需要 JSONP.

改为使用 JSON 并将您的代码更改为

dataType: "json",