使用 Express 4.11 和 bodyParser 使用 JSON
Consuming JSON using Express 4.11 and bodyParser
我快疯了,我在 Whosebug 和网上花了好几个小时,尝试了这个和那个,但仍然无法得到结果。
我是 node.js 的(非常)新手,但已成功按照教程使用 bodyParser.urlencoded
构建(非常)简单的表单,并且我可以成功恢复并显示发布的内容数据。现在我想使用 bodyParser.json()
做同样的事情 - 但无论我尝试什么,结果总是空的。
代码如下:
var express = require('express');
var session = require('cookie-session');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var jsonParser = bodyParser.json();
var app = express();
// JSON testing
app.post('/json-test', jsonParser, function(req, res) {
if (!req.body) return res.sendStatus(400);
console.log(JSON.stringify(req.body));
console.log(req.body.title);
res.status(200).send(req.body.title);
})
// Can't get anything else
.use(function(req, res, next){
res.setHeader('Content-Type', 'text/plain');
res.status(404).send('Page introuvable !');
})
.listen(8090);
这是 curl 请求
$curl -X POST -H "application/json" -d '{"title":"test-title"}' http://localhost:8090/json-test
第一个 console.log 的结果是 {}
而第二个 undefined
.
我做错了什么?
您的 curl 请求不正确,需要添加 "Content-Type":
curl -X POST -H "Content-Type: application/json" \
-d '{"title":"test-title"}' http://localhost:8090/json-test
我快疯了,我在 Whosebug 和网上花了好几个小时,尝试了这个和那个,但仍然无法得到结果。
我是 node.js 的(非常)新手,但已成功按照教程使用 bodyParser.urlencoded
构建(非常)简单的表单,并且我可以成功恢复并显示发布的内容数据。现在我想使用 bodyParser.json()
做同样的事情 - 但无论我尝试什么,结果总是空的。
代码如下:
var express = require('express');
var session = require('cookie-session');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var jsonParser = bodyParser.json();
var app = express();
// JSON testing
app.post('/json-test', jsonParser, function(req, res) {
if (!req.body) return res.sendStatus(400);
console.log(JSON.stringify(req.body));
console.log(req.body.title);
res.status(200).send(req.body.title);
})
// Can't get anything else
.use(function(req, res, next){
res.setHeader('Content-Type', 'text/plain');
res.status(404).send('Page introuvable !');
})
.listen(8090);
这是 curl 请求
$curl -X POST -H "application/json" -d '{"title":"test-title"}' http://localhost:8090/json-test
第一个 console.log 的结果是 {}
而第二个 undefined
.
我做错了什么?
您的 curl 请求不正确,需要添加 "Content-Type":
curl -X POST -H "Content-Type: application/json" \
-d '{"title":"test-title"}' http://localhost:8090/json-test