[英]req.body.data got undefined in nodejs
我的客戶端
$.post("http://localhost:3000/scrape",
{
data: 'something'
},
function(data, status){
console.log(data);
});
我在 node.js 中做什么
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/scrape', function (req, res) {
console.log(req.body.data)
});
但是我在 console.log(req.body.data) 中沒有定義,知道為什么嗎?
您的數據必須是 json 格式。 因為您使用的是bodyParser.json()
。
嘗試在$.post
調用中將 http 標頭、 Content-type
為application/json
並發送有效的 json 結構作為數據
$.ajax({
url: "scrape",
type: "POST",
data: JSON.stringify({ someData : "someData}),
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(data){
console.log(data)
},
error: function(){
console.log('error in sending request')
}
})
console.log(req.body.data)
返回 undefined 因為數據在req.body
你應該console.log(req.body)
並添加app.use(bodyParser.urlencoded({extended: false}));
這樣也可以解析非json格式的數據。
如果你想要req.body.data
有數據,那么提出請求
$.post("http://localhost:3000/scrape",
{
data: {data: 'something'}
},
function(data, status){
console.log(data);
});
您的請求也沒有發送您需要做的任何響應
app.post('/scrape', function (req, res) {
console.log(req.body.data)
res.status(200).json({data: reqr.body.data});
});
希望能幫助到你 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.