简体   繁体   English

在AJAX请求上发送JSON对象,在服务器上未定义

[英]Sending JSON Object on AJAX Request, Undefined on Server

I am using an XMLHttpRequest like this: 我正在使用XMLHttpRequest这样的:

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

to send an object ( this.state.ingredients ) to the server. 将对象( this.state.ingredients )发送到服务器。 I'm pretty confident that it is being sent correctly, because in Chrome Dev Tools under Network tab the request payload looks right. 我非常有信心它能够正确发送,因为在Chrome开发工具的“网络”标签下,请求有效负载看起来正确。 However I've tried a bunch of different things on the server to grab that object and I can't get anything but undefined . 但是我在服务器上尝试了许多不同的事情来抓住这个对象,除了undefined我什么都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. 但我也尝试过使用JSON.parse和其他尝试。 What am I doing wrong here? 我在这里做错了什么?

If you use express, install body-parser : 如果使用express,请安装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;

根据使用的框架,您的请求req.body可能会在req.body

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM