Nodejs Express 发送状态错误

Nodejs Express sendStatus error

Web 应用程序使用 express 作为服务器,nodejs 作为语言,mongodb 作为数据库,mongoose 作为包装器。 Express 是 运行 端口 3000 的服务器,我正在尝试为 collection.

实现基本的 CRUD

我以前用过 restify,通常做 res.send(406, "err - body");不会引起任何问题,但我似乎无法用 express 解决。

查看 express 的文档,res.status(404).send('Bad Request');是您发送带有自定义消息的状态代码的方式。当存在某种无效输入但当我尝试保存到 mongodb

时它会起作用
newSchema.save(function(err){ 
    if (err) {
        res.status(500).send('error saving');
    } else {
        res.sendStatus(200);
    }
});

并调用 res.sendStats(200);它给了我错误:错误:发送后无法设置 headers。使用 httprequester 时,错误为 404 和 Cannot POST /user/create。

您之后是否发送另一个回复?即...也许您正在做类似的事情:

if (!err){
    res.send()
}

无论在何处调用该函数(或在您粘贴的代码之后)。显然,这可能是您的错误来源,因为您将发送两个单独的响应。

显然,将 restify 代码复制到 express 中并不是一个好主意。我有一个 next();它不适用于 express 或者它可以,但截至目前,我不需要使用它。

我改为 res.send(),而不是 res.sendStatus(),而且效果很好。