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));
}
You need multer to get the multipart/form-data.
npm i multer
formdataParser = require('multer')().fields([])
app.use(formdataParser)
Updated according to
https://github.com/expressjs/body-parser/issues/88#issuecomment-173644716 comment
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.