I am trying to send the FormData from React JS to the backend (express node server) as shown below.
I am seeing the empty value for req.body.myFormData (expressTest.js)
.
I tried the suggestions from this post too but no luck. Any help is appreciated.
how do i send FormData to the node server from React js axios post request?
reactTest.js module
myFormData = new FormData();
myFormData.append("userName","TestUser")
myFormData.append("files", file) // input type file
export const sendDocument = async (myFormData) => {
return await axios({
method: 'post',
url: `/sendDocument`,
data: myFormData,
headers: { 'Content-Type': 'multipart/form-data' }
});
};
expressTest.js
const express = require('express')
const axios = require('axios')
const router = express.Router()
router.post('/', (req, res) => {
console.log(req.body.myFormData) //giving undefined //tried req.myFormData too
console.log(JSON.parse(req.body.myFormData.userName))
axios({
method: 'post',
url: '/sendMyUserData',
data: req.body.myFormData,
headers: {
apiKey: 'keytoapi',
'Content-Type': 'multipart/form-data'
}
})
.then(response => {
return res.send(res)
})
.catch(error => {
console.error('error')
}
After adding the multer
, recommended by @con-fused and @Kidas, I can read the FormData in the Express router.
Below is the output.
console.log(req.body)
[Object: null prototype] {
files: '[object File]',
userName: 'TestUser'
}
Now I need to send this to my backend Java end point-Am I sending the right body? it is not hitting my endpoint
@PostMapping(path = "/sendMyUserData", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
public String uploadMyUserData(@RequestPart(value = "files") final MultipartFile[] multipartFiles, @RequestPart(value = "userName", required = true) String userName ) {
return myService.storeFiles(multipartFiles, userName));
}
question from:
https://stackoverflow.com/questions/65928892/how-to-send-form-data-from-react-to-the-node-js-back-end-server 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…