How to send form data from React to the Node JS back end server
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("file", file) //eventually sending the file once it works
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));
}
from Recent Questions - Stack Overflow https://ift.tt/39oRndp
https://ift.tt/eA8V8J
Comments
Post a Comment