David
David

Reputation: 972

Sending JSON Object on AJAX Request, Undefined on Server

I am using an XMLHttpRequest like this:

xml.send(JSON.stringify({ingredients: this.state.ingredients}));

to send an object (this.state.ingredients) to the server. I'm pretty confident that it is being sent correctly, because in Chrome Dev Tools under Network tab the request payload looks right. However I've tried a bunch of different things on the server to grab that object and I can't get anything but undefined.

Currently it looks like this:

router.post('/recipes/:recipe_id/add', function(req, res) {
  let ingredients = req.ingredients;
  console.log(ingredients)
}

but I've also tried using JSON.parse among other attempts. What am I doing wrong here?

Upvotes: 1

Views: 52

Answers (2)

Arkerone
Arkerone

Reputation: 2026

If you use express, install body-parser :

npm install --save body-parser

and use it :

const bodyParser = require('body-parser');
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: true })); 

and try :

let ingredients = req.body.ingredients;

Upvotes: 2

ggradnig
ggradnig

Reputation: 14169

Depending on the used framework, your Request Body will probably be in req.body

Upvotes: 0

Related Questions