如何在节点中编写条件检查?

时间:2018-02-20 20:33:27

标签: javascript json node.js

我收到以下异常:

 throw er; // Unhandled 'error' event
      ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at validateHeader (_http_outgoing.js:503:11)
    at ServerResponse.setHeader (_http_outgoing.js:510:3)
    at ServerResponse.header (/Users/athulmuralidharan/my_documents/MS/MSD/projects/MLL-backEnd/node_modules/express/lib/response.js:730:10)
    at ServerResponse.send (/Users/athulmuralidharan/my_documents/MS/MSD/projects/MLL-backEnd/node_modules/express/lib/response.js:170:12)
    at ServerResponse.json (/Users/athulmuralidharan/my_documents/MS/MSD/projects/MLL-backEnd/node_modules/express/lib/response.js:256:15)
    at /Users/athulmuralidharan/my_documents/MS/MSD/projects/MLL-backEnd/controllers/users.js:56:13
    at model.Query.<anonymous> (/Users/athulmuralidharan/my_documents/MS/MSD/projects/MLL-backEnd/node_modules/mongoose/lib/model.js:3928:16)
    at /Users/athulmuralidharan/my_documents/MS/MSD/projects/MLL-backEnd/node_modules/kareem/index.js:297:21
    at /Users/athulmuralidharan/my_documents/MS/MSD/projects/MLL-backEnd/node_modules/kareem/index.js:135:16
    at process._tickCallback (internal/process/next_tick.js:150:11)

意图:验证返回的对象是否为空 代码:

exports.login = function(req,res,next){

console.log
User.findOne({email: req.body.username,password: req.body.password}, function(err,obj)
{
    if (err)
        res.send(err);

    if (obj == null)
    {
        console.log("null returned");
        res.status(404).send("Oh uh, something went wrong");

    }
    console.log(obj);
    res.json(obj);
}
);

2 个答案:

答案 0 :(得分:1)

如果err是真的,您的程序将res.send,它会向客户端发送标题。

if (err)
    res.send(err);

但是,之后你不会停止你的程序,所以下一个if语句也会运行,并且obj 等于null的可能性,因此您已使用res.send(err),但尝试res.status(404)

if (obj == null)
{
    console.log("null returned");
    res.status(404).send("Oh uh, something went wrong");
}

要解决此问题,您只需在使用res.send后使用else语句或return ::

停止程序
if (err) {
    res.send(err);
} else if (obj == null) {
    console.log("null returned");
    res.status(404).send("Oh uh, something went wrong");
}

替代地

if (err)
    return res.send(err);

if (obj == null) {
    console.log("null returned");
    res.status(404).send("Oh uh, something went wrong");
}

答案 1 :(得分:0)

你真的只是错过了一个事实。

User.findOne({email: req.body.username,password: req.body.password}, function(err,obj) {
    if (err)
        return res.send(err);

    if (obj == null)
    {
        console.log("null returned");
        return res.status(404).send("Oh uh, something went wrong");

    }
    console.log(obj);
    res.json(obj);
});

这是由于您在err出现时发送了多个标题,如错误所示。