UnhandledPromiseRejectionWarning:错误:发送标头后无法设置标头

时间:2018-11-20 11:46:43

标签: node.js express

我是nodejs的新手。我有一个MEAN堆栈项目employeedepartmentuser roles模型。创建employee时,我正在检查departmentuserrole

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'
            });
        });
};

当我尝试创建没有响应的deptIDuserRoleID的员工时,得到的正确响应为not found。但是在终端中出现错误

enter image description here

我认为退货有误,请纠正我!

2 个答案:

答案 0 :(得分:3)

  

响应已发送,MongoDB回调(UserRole)再次发送了响应。您的 Department.findById UserRoles.findById 查询彼此独立,因此此处不需要Promise链接。

关于响应头的书面答案很好,可以在这里找到...

  

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'
    });
}};

答案 1 :(得分:1)

  

发送后无法设置标题

您多次答复该请求。找出导致执行此操作的代码路径并加以解决。

每个请求只能res.status()...一次。