[英]POST 500 (Internal Server Error) can't post form-data with react js on node server
POST https://waste-alert-api.herokuapp.com/datas 500 (Internal Server Error)
我創建了一個 React 項目,我想在其中上傳帶有一些數據的圖像。 除了 post 方法之外,每個方法都可以正常工作。 為了更好地理解,我添加了 React JS 部分以及 Node Js 代碼。
當我用 POSTMAN 測試時,Node Js 服務器工作正常。
反應 JS
const submitPostHandler = async (data) => {
try {
const response = await fetch(
"https://waste-alert-api.herokuapp.com/datas",
{
method: "POST",
body: data,
headers: {
"Content-Type": "multipart/form-data",
Authorization: token,
},
}
);
console.log(response);
} catch (err) {
console.log(err);
}
};
const metaData = {
"wasteType": enteredWasteType,
"location": {
"lat": enteredLat,
"long": enteredLong,
},
};
console.log(metaData);
const data = new FormData();
data.append("image", file);
data.append("data", metaData);
props.submitPostHandler(data);
節點 Js
router.post(
"/datas",
auth,
uploadOptions.single("image"),
async (req, res, next) => {
const file = req.file;
if (!file) return res.status(400).send("No image in the request");
const fileName = file.filename;
const basePath = `${req.protocol}://${req.get("host")}/uploads/`;
console.log(req.body.data);
const newData = JSON.parse(req.body.data);
const data = new Data({
wasteType: newData.wasteType,
location: newData.location,
image: `${basePath}${fileName}`,
owner: req.user._id,
});
try {
await data.save();
res.status(201).send(data);
} catch (e) {
res.send({ e, error: "something is wrong" });
}
}
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.