簡體   English   中英

在AJAX請求上發送JSON對象,在服務器上未定義

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

我正在使用XMLHttpRequest這樣的:

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

將對象( this.state.ingredients )發送到服務器。 我非常有信心它能夠正確發送,因為在Chrome開發工具的“網絡”標簽下,請求有效負載看起來正確。 但是我在服務器上嘗試了許多不同的事情來抓住這個對象,除了undefined我什么都undefined

當前看起來像這樣:

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

但我也嘗試過使用JSON.parse和其他嘗試。 我在這里做錯了什么?

如果使用express,請安裝body-parser:

npm install --save body-parser

並使用它:

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

並嘗試:

let ingredients = req.body.ingredients;

根據使用的框架,您的請求req.body可能會在req.body

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM