我内置了节点2的方法来进行配置文件的GET和POST,并在执行请求时得到:
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;
我无法理解导致此错误的原因,希望对此进行解释。
答案 0 :(得分:1)
您遇到的问题是,您在致电next
之后正在致电res.someMethod
。
调用res.status().json()
时,您告诉express
结束请求并以某种状态和JSON
负载进行响应。调用next
将调用堆栈中的下一个中间件,但是由于您要使用res.someMethod
“结束”请求,因此将没有“下一个”中间件。
通过消除getAll
调用来更改createNew
和next()
中的代码:
async getAll(req, res, next) {
// ...
res.status(200).json(...)
},
async createNew(req, res, next) {
// ...
res.status(201).json(...)
}
请勿同时呼叫next
和res.someMethod
。仅当您要调用堆栈中的下一个中间件时才使用next
,或者当您要结束请求并向发出请求的人返回内容时使用res.someMethod
。