0

I have a frontend in Angular and a backend in node.js with express.

I am doing a POST request in Angular like so:

this.userDetails = {
  address: {
    city: "City"
    country: "CH"
    number: "8"
    road: "Road"
    zip: "1020"
  },
  details: {
    2FA: false
    email: "test@user.io"
    gender: "0"
    name: "User"
    surname: "Name"

  }
}
this.http.post(
  environment.paymentHook + '/customercreate',
  this.userDetails
).subscribe(
  res => resolve(res),
  err => resolve(err)
);

receiving it like so in the back:

app.use(express.json());
app.options('/customercreate', cors(corsOptionsDelegate), function (req, res) { 
  res.end(); 
});
app.post('/customercreate', cors(corsOptionsDelegate), async (request, response) => {
  const body = request.body; // --> this appears empty {} when it should have the this.userDetails content
});

Anybody knows what is my issue here?

mikegross
  • 1,674
  • 2
  • 12
  • 27
  • What is `this.userDetails` when the call is made? – Explosion Pills Jul 09 '20 at 17:40
  • Maybe this helps? https://stackoverflow.com/questions/34444033/express-accessing-angular-http-post-data – MikeOne Jul 09 '20 at 17:42
  • Try looking in your web browsers network tab and see if the http call looks correct. Your angular code looks correct assuming `environment.paymentHook` is right. – Jimmy Arroyo Jul 09 '20 at 17:44
  • @MikeOne This is a really old answer. With the newest version of express there is no need to use bodyParser – mikegross Jul 09 '20 at 17:44
  • @JimmyArroyo Yes, I receive the request on the server and am able to console.log a few things. But the req.body appears empty like `{}` – mikegross Jul 09 '20 at 17:45
  • Can you see the body in the network request in the browser console too? – Jimmy Arroyo Jul 09 '20 at 17:46
  • @JimmyArroyo yes, the body appears in the request payload – mikegross Jul 09 '20 at 17:47
  • What's the content type for the request? Which version of angular are you using? – David Jul 09 '20 at 18:41
  • I faced the same problem. And it was caused because body contents was sent as custom JSON, like your `this.userDetails`. And this is *sometimes* not liked by express. Try converting that custom JSON into a `FormData` object. Check this: https://stackoverflow.com/questions/22783108/convert-js-object-to-form-data – Sergio Jul 10 '20 at 08:28

0 Answers0