【发布时间】:2020-04-18 18:30:55
【问题描述】:
当我将POST 和Content_Type 设置为原始/JSON 时,响应不为空。但是当我尝试将Content_Type 设置为表单数据的POST 数据时,响应返回为空。我该如何解决这个问题?
Postman Screenshot with FormData
但是当我尝试作为原始数据/JSON 时,没关系:
Postman Screenshot with JSON Data
对于原始数据,我的内容类型是:
multipart/form-data; boundary=<calculated when request is sent>
我的 cors 设置是:
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
if (req.method === "OPTIONS") {
res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET");
return res.status(200).json({});
}
next();
});
我的后置路由器是这样的:
router.post("/", upload.single("productImage"), (req, res, next) => {
console.log(req.file);
Category.findById(req.body.categoryID)
.then((category) => {
if (!category) {
return res.status(404).json({
message: "Category not found",
category: category,
});
}
//
const product = new Product({
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
price: req.body.price,
quantity: req.body.quantity,
category: req.body.categoryID,
});
return product.save();
})
.then((result) => {
console.log(result);
res.status(201).json({
message: "Object created succesfully",
product: {
id: result._id,
name: result.name,
price: result.price,
quantity: result.quantity,
category: result.category,
},
});
})
.catch((err) => {
console.log(err), res.status(500).json({ error: err });
});
});
错误是:
UnhandledPromiseRejectionWarning: Error
[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the
client
我该如何解决这个问题?
【问题讨论】:
-
你能解决问题吗?即使我有同样的问题
标签: node.js mongodb rest express cart