使用 Mongoose 预保存挂钩导致:错误 [ERR_HTTP_HEADERS_SENT]:将它们发送到客户端后无法设置 headers
Using Mongoose pre save hook result in: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
我正在尝试连接到 Mongoose 中的保存功能,以便 return 如果架构中未满足特定条件,则会向 REST API 的客户端发送错误。我不能为此使用验证器,因为限制是在架构的多个字段上计算的。
我正在尝试添加以下样式的挂钩:
mySchema.pre('save', function (next) {
if(condition_is_not_met) {
const err = new Error('Condition was not met');
next(err);
}
next();
});
当我尝试调用端点以尝试插入违反挂钩检查条件的 object 时,这会引发错误:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent
to the client
我猜测发生这种情况是因为在写入 header 以将其发送给客户端的路由上继续执行。
router.post('/mySchema', returnType, (req, res) => {
const s = new mySchema(req.body);
s.save((err) => {
if (err) {
const msg = { message: 'Could not add', error: err }; // This is returned to the caller
res.status(500);
res.send(msg);
}
res.status(200);
res.send(s);
});
});
我该如何解决这个问题?我一直在搜索,但到目前为止我发现的主题并不能帮助我解决我的问题。他们只是帮我找出了原因,却没有提供有效的解决方案。
您是否尝试过为成功响应设置一个 else 分支?因为即使对象无效,成功响应仍然会被执行。像下面这样尝试
router.post("/mySchema", returnType, (req, res) => {
const s = new mySchema(req.body);
s.save(err => {
if (err) {
const msg = { message: "Could not add", error: err };
res.status(500);
res.send(msg);
} else {
res.status(200);
res.send(s);
}
});
});
请原谅我的代码格式,我AFK
我正在尝试连接到 Mongoose 中的保存功能,以便 return 如果架构中未满足特定条件,则会向 REST API 的客户端发送错误。我不能为此使用验证器,因为限制是在架构的多个字段上计算的。
我正在尝试添加以下样式的挂钩:
mySchema.pre('save', function (next) {
if(condition_is_not_met) {
const err = new Error('Condition was not met');
next(err);
}
next();
});
当我尝试调用端点以尝试插入违反挂钩检查条件的 object 时,这会引发错误:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
我猜测发生这种情况是因为在写入 header 以将其发送给客户端的路由上继续执行。
router.post('/mySchema', returnType, (req, res) => {
const s = new mySchema(req.body);
s.save((err) => {
if (err) {
const msg = { message: 'Could not add', error: err }; // This is returned to the caller
res.status(500);
res.send(msg);
}
res.status(200);
res.send(s);
});
});
我该如何解决这个问题?我一直在搜索,但到目前为止我发现的主题并不能帮助我解决我的问题。他们只是帮我找出了原因,却没有提供有效的解决方案。
您是否尝试过为成功响应设置一个 else 分支?因为即使对象无效,成功响应仍然会被执行。像下面这样尝试
router.post("/mySchema", returnType, (req, res) => {
const s = new mySchema(req.body);
s.save(err => {
if (err) {
const msg = { message: "Could not add", error: err };
res.status(500);
res.send(msg);
} else {
res.status(200);
res.send(s);
}
});
});
请原谅我的代码格式,我AFK