Home > Software engineering >  POSTing from Angular to Node. Getting empty body on node
POSTing from Angular to Node. Getting empty body on node

Time:10-16

Im posting two fields in Angular to a NodeJs endpoint.

I usually post on the body and everything is perfect at Node, but this time, I have to post a form to upload a file.

So this is my code for posting the form data (Angular side):

var APIURL = sessionStorage.getItem('endPoint')   "profile/updateeocoverage"; 
let formData = new FormData();
formData.append("data", JSON.stringify(this.payLoad));
if (this.eofile) {
  formData.append("myfile", this.eofile, this.eofile.name);
}
this.httpClient.post(APIURL,  formData).subscribe(
  result => {
  ....

My problem is that I always retrieved the body at node as follows:

router.post('/updateeocoverage', async   (req, res, next) => {
    console.log(req.body)
    return;
    ....

But with the method Im using now in Angular, req.body is retrieving {}

Is the POST wrong, or the router wrong at Node side?

Thanks.

CodePudding user response:

First thing to do is ensure that the body isn't empty before making the request, so do a console.log before the request:

console.log(formData);
this.httpClient.post(APIURL,  formData).subscribe(
  result => {
  ....

After that, if the body is filled correctly, try to put the body like this on the request method:

this.httpClient.post(APIURL,  {formData})

or

   this.httpClient.post(APIURL,  {
     "field1": formData.field1,
     ...
})

and if these two things don't correct your issue, problaby you have something wrong on back-end side

CodePudding user response:

Try using Multer

npm i multer

const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })
router.post('/updateeocoverage', upload.single('myfile'), function (req, res, next) {
    res.json(JSON.parse(req.body.data))
  })

You will need to indicate the destination folder (line 2) and work out the file name, extension, etc.

  • Related