1

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?

2
  • Hi please you should first do something like this to debug before the xml.send console.log(this.state.ingredients); This is to ensure that the this.state.ingredients isn't the one that is undefined Commented Jan 7, 2018 at 0:37
  • Have you tried logging the contents of req? Commented Jan 7, 2018 at 0:55

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.