我知道这个问题已经被问过多次了,但是我一直在四处张望,但仍然找不到我的问题的答案。
这是我的代码,在定义路由之前,请确保使用和配置主体解析器。我仅将.json()与bodyParser一起使用,因为现在我仅测试POST函数,但我什至尝试使用app.use(bodyParser.urlencoded({Extended:true}));
var express = require('express'),
bodyParser = require('body-parser'),
app = express();
app.use(bodyParser.json());
app.set('port', (process.env.PORT || 5000));
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'))
});
app.post('/itemSearch', function(req, res) {
//var Keywords = req.body.Keywords;
console.log("Yoooooo");
console.log(req.headers);
console.log(req.body);
res.status(200).send("yay");
});
这是我使用 postman 测试此路线的方法。
这是我收到的回复
Node app is running at localhost:5000
Yoooooo
{ host: 'localhost:5000',
connection: 'keep-alive',
'content-length': '146',
'cache-control': 'no-cache',
origin: 'chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop',
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundarynJtRFnukjOQDaHgU',
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',
'postman-token': '984b101b-7780-5d6e-5a24-ad2c89b492fc',
accept: '*/*',
'accept-encoding': 'gzip, deflate',
'accept-language': 'en-GB,en-US;q=0.8,en;q=0.6' }
{}
在这一点上,我将非常感谢您的帮助。谢谢。
最佳答案
需要使用Body-Parser的AFAIK:https://github.com/expressjs/body-parser
bodyParser = require('body-parser').json();
app.post('/itemSearch', bodyParser, function(req, res) {
//var Keywords = req.body.Keywords;
console.log("Yoooooo");
console.log(req.headers);
console.log(req.body);
res.status(200).send("yay");
});
然后尝试使用PostMan将正文设置为
raw
json:{
"test": "yay"
}