Javascript 在express app中的函数中返回响应
正如我们所知,我们必须在express应用程序中返回响应,以避免“发送到客户端后无法设置头”错误。 然而,在下面的代码中,我试图返回响应,但它返回到我们的路由器,并导致上述错误。如何在函数中直接返回响应Javascript 在express app中的函数中返回响应,javascript,node.js,express,Javascript,Node.js,Express,正如我们所知,我们必须在express应用程序中返回响应,以避免“发送到客户端后无法设置头”错误。 然而,在下面的代码中,我试图返回响应,但它返回到我们的路由器,并导致上述错误。如何在函数中直接返回响应 router.post("/admins", async function (req, res) { var newAdminObj = await newAdminObjectDecorator(req.body, res); var newAdmin = new Admi
router.post("/admins", async function (req, res) {
var newAdminObj = await newAdminObjectDecorator(req.body, res);
var newAdmin = new Admins(newAdminObj)
newAdmin.save(function (err, saveresult) {
if (err) {
return res.status(500).send();
}
else {
return res.status(200).send();
}
});
});
// the function
var newAdminObjectDecorator = async function (entery, res) {
// doing some kinds of stuff in here
// if has errors return response with error code
if (err) {
// app continues after returning the error header response
return res.status(500).send();
}
else {
return result;
}
}
切勿运行控制器功能以外的响应操作。让另一个函数返回答案并根据答案进行决定
router.post("/admins", async function (req, res) {
var newAdminObj = await newAdminObjectDecorator(req.body);
if (newAdminObj instanceof Error) {
return res.status(500).send()
}
var newAdmin = new Admins(newAdminObj)
newAdmin.save(function (err, saveresult) {
if (err) {
return res.status(500).send();
}
else {
return res.status(200).send();
}
});
});
// the function
var newAdminObjectDecorator = async function (entery) {
// doing some kinds of stuff in here
// if has errors return response with error code
if (err) {
// app continues after returning the error header response
return err;
}
else {
return result;
}
}
只需抛出一个错误而不是res.status(500)。谢谢,但这是最佳实践吗?你能解释更多关于投掷和其他解决这个问题的方法(作为回答)吗?Teşekkür ederim。