'getting error when sending files to backend react node js
I am getting error of undefined when i send a file from react to backend, i am unable to understand the error. i am sending a image which will be uploaded in cloudinary but my backend could not get the image data i don't know why this happening. here's the code
My React js code
const handleFileUpload = async (e)=>{
setprofilePic({file: URL.createObjectURL(e.target.files[0])});
const imageFile = e.target.files[0];
const formData = new FormData();
formData.append('image', imageFile);
const result = await fetch(`${host}/fgrapi/auth/setprofileimg`, {
method: 'PUT',
headers: {
"Content-Type":"multipart/form-data" ,
'auth-token': localStorage.getItem('token')
},
body: formData
})
const data = await result.json();
}
My Backend Code (I am using controllers) Routes
router.put('/setprofileimg', fetchuser, authController.setProfileImage)
setProfileImage: async (req, res)=>{
try{
userId = req.user.id;
const image = req.files;
console.log(image); //I am getting undefined here
cloudinary.uploader.upload(image.tempFilePath, async function (error, result) {
const user = await User.findByIdAndUpdate(userId, {profilepic: result.secure_url}, {new: true});
});
}
catch(error){
console.error(error.message);
res.status(500).send("Internal Server Error Occured");
}
},
My server file
const express = require('express');
const connectToMongo = require('./db');
const cors = require('cors')
const fileUpload = require('express-fileupload');
connectToMongo();
const app = express();
const port = process.env.PORT || 1000;
app.use(cors());
app.use(fileUpload({
useTempFiles: true
}));
app.use(express.json());
// Available routes
app.use('/fgrapi/auth', require('./routes/auth'));
app.listen(port,()=>{
console.log("Connection Success");
})
Solution 1:[1]
You need a middleware for handling multipart/form-data in your backend. Use multer or some other available pkg for reading form-data.
You can refer from here: https://www.npmjs.com/package/multer
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Shivam Chamoli |