【发布时间】:2021-10-05 02:01:35
【问题描述】:
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" });
}
}
);
【问题讨论】:
-
它是否至少返回错误消息“有问题”?
-
@GrafiCode 不,我得到的回复不是这个
Response {type: "cors", url: "https://waste-alert-api.herokuapp.com/datas", redirected: false, status: 500, ok: false, …} body: (...) bodyUsed: false headers: Headers {} ok: false redirected: false status: 500 statusText: "Internal Server Error" type: "cors" url: "https://waste-alert-api.herokuapp.com/datas" -
啊,这是一个 CORS 错误。请看一下这个线程,它是关于 ReactJS 获取和 CORS 错误的:stackoverflow.com/questions/48562406/…
-
我处理了 CORS 并发布了 json 数据没有问题,但是当我尝试表单数据时,问题就来了......
-
关于 PostMan,这很有趣:academind.com/tutorials/cross-site-resource-sharing-cors/….
标签: javascript node.js reactjs server