How to properly send and receive JSON data in AngularJS POST request to Node.js API?

Hey everyone, I’m having trouble with my AngularJS and Node.js setup. I’m trying to send login info from my Angular app to a Node.js API, but something’s not right.

When I check the request.body on the Node.js side, the data looks weird. It’s like this:

{ '{"email": "[email protected]", "password": "secret123"}': '' }

I can’t figure out how to get the email and password from this. Here’s what I’ve got:

Angular side:

function sendLoginInfo(userCredentials) {
  $http.post('/api/authenticate', userCredentials, {
    headers: {'Content-Type': 'application/x-www.form-urlencoded'}
  }).then(
    response => console.log('Success:', response),
    error => console.log('Error:', error)
  );
}

Node.js side:

app.post('/api/authenticate', (req, res) => {
  console.log('User email:', req.body.email); // This is undefined
  console.log('Received data:', req.body);
});

What am I doing wrong? How can I fix this so I can access the email and password properly? Thanks for any help!

I’ve run into this issue before, and it’s usually related to how the data is being sent and parsed. Here’s what worked for me:

  1. On the Angular side, try changing your Content-Type to ‘application/json’ instead of ‘x-www.form-urlencoded’.

  2. Make sure you’re stringifying your data before sending it:

$http.post('/api/authenticate', JSON.stringify(userCredentials), {
  headers: {'Content-Type': 'application/json'}
})
  1. On the Node.js side, ensure you’re using the proper middleware to parse JSON. If you’re using Express, add this before your routes:
app.use(express.json());

This should allow you to access req.body.email and req.body.password directly.

Remember to handle potential errors, like invalid JSON, on the server side. Hope this helps!

From my experience, the issue lies in how you’re handling the data transmission. On the Angular side, you should indeed use ‘application/json’ as the Content-Type. However, there’s no need to stringify the data manually - Angular’s $http service does this for you. Just adjust your code like this:

$http.post('/api/authenticate', userCredentials, {
  headers: {'Content-Type': 'application/json'}
})

For the Node.js part, ensure you’ve set up body-parsing middleware correctly. If you’re using Express 4.16+, you can use the built-in express.json() middleware:

app.use(express.json());

Place this before your route definitions. After these changes, you should be able to access req.body.email and req.body.password without issues. Remember to implement proper error handling and input validation for production use.

yo, i had the same prob. try changing ur content-type to ‘application/json’ in the angular bit. also, make sure ur using express.json() middleware on the node side. that should sort it. good luck mate!