Error [ERR_HTTP_HEADERS_SENT]:在Node.js中更新配置文件API时,不能在发送到客户端后



我是Node.js的新手,我遇到了一些问题。

Error [ERR_HTTP_HEADERS_SENT]:在发送到客户端后不能设置报头
在new NodeError (node:internal/errors:393:5)
在ServerResponse。setHeader (node:_http_outgoing:644:11)
at ServerResponse。头(F: Node_js 项目Node_js node_modules 表达 lib response.js: 794:10)

exports.update_profile = async (req, res) => {
try {
let rules =
{
username: req.body.username,
email: req.body.email,
mobile: req.body.mobile,
companyname: req.body.companyname,
};
if (req.files && req.files.Profile_images) {
req.body['Profile_images'] = req.files.Profile_images;
}
const user = new User(req.body, rules);
user.save(err => {
if (err) {
res.status(500).send({ message: err });
return;
}
});
let current_user = req.User;
if (req.files && req.files.Profile_images) {
var image_file = req.files.Profile_images;
var image_file_name = Date.now() + '-Profile-images-' + image_file_name;
var image_path = publicPath + '/Profile_images/' + image_file_name;
await image_file.mv(image_path);
if (current_user.profile_image && current_user.profile_image == '') {
let old_path = publicPath + '/Profile_images/' + current_user.Profile_images;
if (fs.existsSync(old_path)) {
fs.unlinkSync(old_path);
}
}
} else {
var image_file_name = current_user.Profile_images;
}
await User.updateOne({
_id: current_user._id
}, {
username: req.body.username,
email: req.body.email,
mobile: req.body.mobile,
companyname: req.body.companyname,
profile_image: image_file_name,
profession: req.body.profession ? req.body.profession : ''
});
let userData = await User.findOne({ _id: current_user._id })
let jwt_secret = process.env.JWT_SECRET || 'mysecret';
let token = jwt.sign({
data: userData
}, jwt_secret, { expiresIn: '12h' });
return res.status(200).send({ message: 'Profile Updated Successfully Updated', data: userData, token: token });
} catch (error) {
return res.status(404).send({ message: error.message });
}
}

这是我的代码更新配置文件我可以知道我的代码有什么问题吗?

user.save()的错误处理程序抛出一个错误->500响应已发送到客户端,但代码继续->ERR_HTTP_HEADERS_SENT。请更改代码:

来自:

user.save(err => {
if (err) {
res.status(500).send({ message: err });
return;
}
});

To:await user.save()

然后它会记录一些更有用的东西。