Error [ERR_HTTP_HEADERS_SENT]:发送到客户端后不能设置报头.为什么? &g



我在MognoDB中保存图像文件时遇到了问题。它说错误

(node:14849) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to client

当我搜索错误解决方案时,据说我在发送结果之后才发送结果。我正在检查我的代码,它不是那样的。有人能帮我找到这个错误吗?

imageUpload.js

const multer = require("multer");
const uploadImage = require("../../models/fileUpload");
const Storage = multer.diskStorage({
destination: "uploads",
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
cb(null, file.fieldname + "-" + uniqueSuffix);
},
});
const upload = multer({
storage: Storage,
limits: {
fileSize: 1024 * 1024 * 5,
},
}).single("testImage");
const imageUpload = async (req, res) => {
try {
upload(req, res, (err) => {
if (err)
res.status(400).json({
success: false,
message: "Saving Failed",
});
const newImage = new uploadImage({
name: req.body.name,
image: {
data: req.body.image,
contentType: "image/png",
},
});
newImage
.save()
.then(() => {
res.status(201).json({
success: true,
msg: "Saved Successfully",
});
})
.catch((error) => {
res.status(500).json({
success: false,
msg: error.data,
});
});
});
} catch (err) {
console.log(err);
}
};
module.exports = { imageUpload };

在向客户端发送响应之前返回添加返回在您发送的每个响应之前,它将修复错误,这也是一个好习惯

我无法正确定义if

下面是重写的代码。

imageUpload.js

const multer = require("multer");
const uploadImage = require("../../models/fileUpload");
// const Storage = multer.diskStorage({
//   destination: "uploads",
//   filename: function (req, file, cb) {
//     const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
//     cb(null, file.fieldname + "-" + uniqueSuffix);
//   },
// });
const upload = multer({
// storage: Storage,
limits: {
fileSize: 1024 * 1024 * 5,
},
}).single("testImage");
const imageUpload = async (req, res) => {
try {
upload(req, res, (err) => {
if (err) {
res.status(400).json({
success: false,
message: "Saving Failed",
});
} else {
const newImage = new uploadImage({
name: req.body.name,
image: {
data: req.body.image,
contentType: "image/png",
},
});
newImage
.save()
.then(() => {
res.status(201).json({
success: true,
msg: "Saved Successfully",
});
})
.catch((error) => {
res.status(500).json({
success: false,
msg: error.data,
});
});
}
});
} catch (err) {
console.log(err);
}
};
module.exports = { imageUpload };

相关内容

  • 没有找到相关文章

最新更新