UnhandledPromiseRejectionWarning:错误:发送后无法设置标头[重复]
Posted
技术标签:
【中文标题】UnhandledPromiseRejectionWarning:错误:发送后无法设置标头[重复]【英文标题】:UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent [duplicate] 【发布时间】:2019-04-22 20:35:16 【问题描述】:我是 nodejs 的新手。我有一个 MEAN 堆栈项目 employee
、department
和 user roles
模型。在创建employee
时,我正在检查department
和userrole
const mongoose = require('mongoose');
const Employee = require('../models/employee');
const UserRoles = require('../models/userRole');
const Department = require('../models/department');
const _ = require('lodash');
exports.create_employee = (req, res, next) =>
Department.findById(req.body.deptID)
.then( dept =>
if( !dept )
return res.status(404).json(
message: 'Department not found'
);
return UserRoles.findById(req.body.userRoleID)
.then( role =>
if( !role )
return res.status(404).json(
message: 'User role not found'
);
const employee = new Employee(
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
designation: req.body.designation,
doj: req.body.doj,
dob: req.body.dob,
bloodGroup: req.body.bloodGroup,
deptID: req.body.deptID,
userRoleID: req.body.userRoleID,
empCode: req.body.empCode
);
return employee.save();
)
)
.then(result =>
let ob = _.omit(result, ['__v']);
res.status(201).json(
createdEmployee: ob
);
)
.catch(err =>
res.status(500).json(
message: 'Internal Server Error'
);
);
;
当我尝试使用deptID
和userRoleID
创建一个员工时,它们在响应中不存在,我得到正确的响应为not found
。但在终端出现以下错误
我认为我做错了回报,请纠正我!
【问题讨论】:
提示。您在可能应该抛出错误的地方链接承诺并返回值。 【参考方案1】:响应已发送,MongoDB 回调 (UserRole) 再次发送响应。您的 Department.findById 和 UserRoles.findById 查询彼此独立,因此此处不需要 Promise 链接。
可以在此处找到关于 Response 标头的写得很好的答案...
Error: Can't set headers after they are sent to the client
你可以试试这个修改后的代码。
exports.create_employee = async (req, res, next) =>
try
let dept = await Department.findById(req.body.deptID);
if (!dept)
return res.status(404).json(
message: 'Department not found'
);
let role = await UserRoles.findById(req.body.userRoleID);
if (!role)
return res.status(404).json(
message: 'User role not found'
);
// onward code will execute only when role and dept exists.
const employee = new Employee(
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
designation: req.body.designation,
doj: req.body.doj,
dob: req.body.dob,
bloodGroup: req.body.bloodGroup,
deptID: req.body.deptID,
userRoleID: req.body.userRoleID,
empCode: req.body.empCode
);
const result = await employee.save();
let ob = _.omit(result, ['__v']);
res.status(201).json(
createdEmployee: ob
);
catch (err)
res.status(500).json(
message: 'Internal Server Error'
);
;
【讨论】:
【参考方案2】:发送后无法设置标头
您多次回复请求。找出导致此问题的执行代码路径并修复它们。
对于每个请求,您应该只res.status()...
一次。
【讨论】:
以上是关于UnhandledPromiseRejectionWarning:错误:发送后无法设置标头[重复]的主要内容,如果未能解决你的问题,请参考以下文章
[Unhandled promise rejection: TypeError: null is not an object (evaluating '_reactNativeImageCropPic