seo*_*gju 15 node.js express postman
我知道这已被多次询问,但我一直在四处寻找,但仍无法找到问题的答案.
这是我的代码,我确保在定义路由之前使用和配置主体解析器.我只使用.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");
});
Run Code Online (Sandbox Code Playgroud)
这是我收到的回复
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' }
{}
Run Code Online (Sandbox Code Playgroud)
在这一点上,我真的很感激任何帮助.谢谢.
nak*_*kwa 14
AFAIK你需要使用Body-Parser: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");
});
Run Code Online (Sandbox Code Playgroud)
然后尝试使用PostMan将主体设置为rawjson:
{
"test": "yay"
}
Run Code Online (Sandbox Code Playgroud)
form-data我想添加一个答案,因为即使我添加Content-Type: multipart/form-data到标头(这在文档中被列为正确的标头类型) ,发送工作似乎也遇到困难。我想知道是否因为在 Express 中使用 BodyParser,数据必须以 JSON 原始形式输入。我发誓我form-data之前就已经上班了,唉。
这是我如何能够req.body不为空的:
Content-Type: application/json
Run Code Online (Sandbox Code Playgroud)
旁注:有关所有可用标头内容类型值的堆栈溢出文章的有趣链接。
raw选择单选按钮,并且JSON选择最右侧的下拉列表:req.body我的 Express 应用程序,我会看到打印的内容:| 归档时间: |
|
| 查看次数: |
22780 次 |
| 最近记录: |