Reputation: 75
I'm trying to send FormData to nodeJs. I appended the values 'id'
and 'photo'
to the form data. In the front-end, I can clearly see that the FormData is there in the browser's console log, but it is undefined in the nodeJs backend
the backend:
const random = Math.floor(Math.random() * 100000) + 10000;
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './client/public/images');
},
filename: function (req, file, cb) {
cb(null, random.toString() + new Date().getTime() + '.jpg');
},
});
const move = multer({ storage: storage });
const upload = move.single('photo');
router.get('/upload-photo', upload, (req, res) => {
const id = req.body.id;
const photo = req.files['photo'][0].filename;
db.query(
'UPDATE users SET photo = ? WHERE id = ?',
[photo, id],
function (err, rows, fields) {
if (err) throw err;
if (rows.length >= 1) {
rows.map((entry) => {
const user = {};
COLUMNS.forEach((c) => {
user[c] = entry[c];
});
const theUser= {
id: user.id,
photo: user.photo,
};
res.json(theUser);
});
} else {
return res.status(200).json({});
}
}
);
});
The function :
function photoUpload() {
const photoData = new FormData();
photoData.append('id', id);
photoData.append('photo', photoFile);
dispatch(uploadPhoto(photoData));
}
the uploadPhoto action:
export const uploadPhoto = (photoData) => (dispatch) => {
axios
.get(`/api/user/upload-photo`, photoData)
.then((res) => {
dispatch(getPhotos());
})
.catch((err) => {
let message = typeof err.response != 'undefined' ? err.response.data : {};
dispatch({
type: GET_ERRORS,
payload: message,
});
});
};
I don't know if it matters or not, but there is another route like this in a different api file and it works fine. This is basically the same code as that one with the only difference being that the other route uploads multiple files along with multiple req.body data. And that one works perfectly
Upvotes: 1
Views: 1180
Reputation: 75
Instead of:
const photo = req.files['photo'][0].filename;
I had to do:
const photo = req.file.filename;
since it was just only one file
Upvotes: 1