node.js - 未处理的PromiseRejection警告: Error: Can't set headers after they are sent

标签 node.js express

我是 Nodejs 新手。我有一个 MEAN 堆栈项目 employee , departmentuser 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'
            });
        });
};

当我尝试使用 deptID 创建员工时和userRoleID哪些不存在于响应中,我得到的正确响应为 not found 。但在终端中出现以下错误

enter image description here

我认为我做了一些错误的返回,请纠正我!!

最佳答案

Response is already sent and again a response is being sent by MongoDB callback (UserRole). Your Department.findById and UserRoles.findById queries are independent to each other so here Promise chaining not required.

可以在此处找到有关响应 header 的写得很好的答案...

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

关于node.js - 未处理的PromiseRejection警告: Error: Can't set headers after they are sent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53392335/

相关文章:

javascript - 使用 Node mssql 准备语句的事务

javascript - Fastify - 如何使用 fastify-multipart 获取非文件字段

JavaScript 堆内存不足 - 插入 mongodb 时出错

ios - React Native 无效的 podfile "No such file or directory - ./node_modules/.bin/react-native."

javascript - 使用 bcrypt 获取有效密码

javascript - 如何使用 node.js (express) 处理 get 请求

node.js - Express Node.js Controller 不等待数据操作并返回旧数据

node.js - 向移动用户提供不同的内容?

javascript - GraphQL - 将非特定对象的对象作为参数传递

javascript - Jade 遍历对象并将 child 分配给 parent