如何解决NodeJS GET / POST请求中的错误[ERR_HTTP_HEADERS_SENT]

问题描述 投票:0回答:1

我内置了用于获取和发布配置文件的节点2方法,并且在执行请求时得到了:Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

我还添加了一种集中式方法来处理错误,我不确定是否是导致错误的原因。顺便说一句,GET或POST都没有失败,我可以看到结果并将记录发送到DB,但是我在控制台上看到了以上错误。

方法:

// Profile model
const { Profile } = require("../models");
const { ErrorHandlers } = require("../utilities");

// Profiles Controller
const ProfilesController = {
    // To GET ALL the profiles
    async getAll(req, res, next) {
        try {
            // Profiles from DB & count how many
            const profiles = await Profile.find({});
            const profilesCount = await Profile.countDocuments();

            // No profiles from DB then error via handler
            if (profiles.length === 0) {
                throw new ErrorHandlers.ErrorHandler(
                    404,
                    "No profiles have been found"
                );
            }
            // Sending response with results
            res.status(200).json({ count: profilesCount, profiles });
            // Passing the error to the error-handling middleware in server.js
            next();
        } catch (err) {
            // Internal server error
            next(err);
        }
    },

    // To Create a new profile
    async createNew(req, res, next) {
        console.log(req.body);
        // Profile init
        const profile = new Profile({
            ...req.body
        });

        try {
            // Await the save
            const newProfile = await profile.save();
            // If save fail send error via handler
            if (!newProfile) {
                throw new ErrorHandlers.ErrorHandler(
                    400,
                    "Profile cannot be saved"
                );
            }

            // All OK send the response with results
            res.status(201).json({ message: "New profile added", newProfile });
            next();
        } catch (err) {
            // Errors
            next(err);
        }
    }
};

module.exports = ProfilesController;

错误处理程序:

class ErrorHandler extends Error {
    constructor(statusCode, message) {
        super();
        this.statusCode = statusCode;
        this.message = message;
    }
}

const handleError = (err, res) => {
    const { statusCode, message } = err;
    res.status(statusCode).json({
        status: "error",
        statusCode,
        message
    });
};
module.exports = {
    ErrorHandler,
    handleError
};

错误处理程序还具有在server.js中调用的中间件

const { ErrorHandlers } = require("../utilities");

const errors = (err, req, res, next) => {
    return ErrorHandlers.handleError(err, res);
};

module.exports = errors;

我不知道是什么导致了此错误,希望对此进行解释。

node.js
1个回答
0
投票

您的问题是,您在致电next之后要致电res.someMethod

[当您呼叫res.status().json()时,您告诉express结束请求并以某些状态和JSON有效负载进行响应。调用next将调用堆栈中的下一个中间件,但是由于您要使用res.someMethod“结束”请求,因此将没有“下一个”中间件。

© www.soinside.com 2019 - 2024. All rights reserved.