POST https://waste-alert-api.herokuapp.com/datas 500 (Internal Server Error)
I have created a React Project where I want to upload an Image with some data. Every method works fine except the post method. For better understanding, I added React JS part as well as Node Js code.
Node Js server works fine when I tested with POSTMAN.
React 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);
Node 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" });
}
}
);
I had a similar issue with my MERN app. My client package.json file included proxy key with Heroku created app address. But it caused 500/503 internal server errors when running app on localhost. Firstly I followed this solution and installed http-proxy-middleware into client folder. And secondly, in my axios.post method I changed error handling from err to err.response.data as suggested here.