You can transfer an image from React to Node by using a form data object to wrap the image data and sending it through an HTTP request to the backend. Here's an example:
In your React component:
const formData = new FormData();
formData.append("image", imageFile);
fetch("/upload", {
method: "POST",
body: formData,
})
.then(response => {
// handle response from backend
})
.catch(error => {
// handle error
});
In your Node backend:
const multer = require("multer");
const upload = multer().single("image");
app.post("/upload", upload, (req, res) => {
// req.file contains the image file data
});
fs.writeFile(`./uploads/${req.file.originalname}`, req.file.buffer, (err) => {
if (err) {
// handle error
}
else {
// send response back to client
res.status(200).send({ message: "Image uploaded successfully" });
}
});
By wrapping the image file data in a form data object and parsing it on the backend using a library like Multer, you can ensure that the backend is able to detect the response file.
Asked: 2023-07-01 14:20:20 +0000
Seen: 10 times
Last updated: Jul 01 '23