【问题标题】:Sending JSON error from Node.js backend to iPhone frontend: "Error: Can't set headers after they are sent."从 Node.js 后端向 iPhone 前端发送 JSON 错误:“错误:发送后无法设置标头。”
【发布时间】:2013-01-30 00:00:34
【问题描述】:

我是 Node.js 的新手。我将它用作 iPhone 客户端的服务器后端。我正在使用 JSON 调用 POST:{firstname: "bob", email : bob@someemail.com}

node.js 代码如下所示(使用 Express 和 Mongoose):

var User = new Schema({
    firstname   : { type: String, required: true}
    , email     : { type: String, required: true, unique : true}

});
var User = mongoose.model('User', User);

对于 POST,

app.post('/new/user', function(req, res){

    // make a variable for the userData
    var userData = {
        firstname: req.body.firstname,
        email: req.body.email
    };

    var user = new User(userData);

    //try to save the user data
    user.save(function(err) {
        if (err) {
            // if an error occurs, show it in console and send it back to the iPhone
            console.log(err);
            res.json(err);
        }
        else{
            console.log('New user created');
        }
    });

    res.end();
}); 

现在,我正在尝试使用相同的电子邮件创建重复用户。由于我对电子邮件的“独特”约束,我希望这会引发错误——确实如此。

但是,node.js 进程终止并显示“错误:发送后无法设置标头。”

我希望能够在诸如此类的情况下将消息发送回 iPhone 客户端。例如,在上面,我希望能够将 JSON 发送回 iPhone,说明新用户创建的结果(成功或失败)。

谢谢!

【问题讨论】:

  • 注释掉最后一个 res.end 解决了这个问题。那么也许 res.send 和 res.json 会自己调用 res.end?
  • 我认为没有。在您的代码中,如果出现错误,首先调用res.end,而不是res.json,因为您的代码是异步执行的。

标签: node.js mongodb express mongoose


【解决方案1】:

这是因为您的代码具有异步特性。 res.end()user.save 的回调函数之前运行,您应该将res.end() 放在该回调中(最后)。

这样:

  user.save(function(err) {
    if (err) {
        // if an error occurs, show it in console and send it back to the iPhone
        console.log(err);
        return res.json(err);
    }
    console.log('New user created');
    res.end();
});

【讨论】:

    【解决方案2】:

    使用适当的 http 状态发送您的错误,您有足够的 4xx 来执行此操作。

     res.json(420, err);
    

    这样,你只需要在你的 http fetch 中解析消息,使用 jquery 它会给出类似的东西:

    jQuery.ajax({
      ...
      error: function (xhr, ajaxOptions, thrownError) {
        if(xhr.status == 420) {
          JSON.parse(xhr.responseText);
        }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-22
      • 1970-01-01
      • 2023-03-29
      • 2012-07-25
      • 2015-05-21
      • 2015-09-08
      相关资源
      最近更新 更多