I'm trying to send a image from a react front end to a node.js backend using axios, with help from this post: How do you send images to node js with Axios? I managed to get it from the frontend to the backend, but when I console.log
the req.files
and the req.body
it's undefined
or empty. I can't figure out how to fix it. Can anyone help me?
Here is the code for the app.js
React frontend:
import "./App.css";
import React, { useState } from "react";
import axios from "axios";
function App() {
const [image, setImage] = useState("");
function handleImage(e) {
console.log(e.target.files);
setImage(e.target.files[0]);
}
function handleApi() {
const formData = new FormData();
formData.append("image", image);
console.log(formData)
axios
.post("http://localhost:3001/users/editprofile/1", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((res) => {
console.log(res);
});
}
return (
<div>
<input type="file" name="file" onChange={handleImage} />
<button onClick={handleApi}>submit</button>
</div>
);
}
export default App;
and this is the node.js back end:
router.post("/editprofile/:id", async (req, res) => {
const id = req.params.id;
console.log(req.files)
console.log(req.body)
//console.log(req)
//const { pfp } = req.files;
// if (pfp) {
// await pfp.mv(`${__dirname}/images/profile_pictures/pfp_${id}}`);
// }
//Would make the code "save" by not allowing any uploads at allz`
//if (/^image/.test(image.mimetype)){
// console.log("not an image");
// return res.sendStatus(400);
//}
res.sendStatus(200);
});
When I log just the req
I get a response to the Axios is sending something to the backend and when I look into the network and console in the browser I get the following things:
The network tab in the browser:
Thanks in advance for the help!!