1. nodejs express接收POST参数的问题
通过CURL或者POSTMAN工具向后台服务发送POST请求时,nodejs express无法获得相关参数,req.body是undefined,查询各种资料,多数是简单说设置 bodyParser.json()或者bodyParser.urlencoded({ extended: false }),但均没有完整说明,现整理如下:
2. 解决办法
(1)在路由页面文件引入body-parser
var bodyParser = require(‘body-parser’);
// create application/json parser
var jsonParser = bodyParser.json();
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false });
(2)在POST路由处理函数中使用body-parser
根据客户端传输参数格式选择不同接收方式,比如:
接收 x-www-form-urlencoded 参数:“name=xxx&mobile=133897”
router.post(’/add’, urlencodedParser, function(req,res) {
console.log(req.body);
}
接收 json 参数:{“name”:“xxx”,“mobile”:“133897”}
router.post(’/add’, jsonParser , function(req,res) {
console.log(req.body);
}
3. 测试方法
(1)CURL工具
curl -X POST -H “Content-Type: application/x-www-form-urlencoded” -d “name=xxx&mobile=133897” http://192.168.250.128:9090/api/cycloper/add
curl -X POST -H “Content-Type: application/json” -d {“name”:“xxx”,“mobile”:“133897”} http://192.168.250.128:9090/api/cycloper/add
(2)POSTMAN插件
POST /api/cycloper/add HTTP/1.1
Host: 192.168.250.128:9090
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded
name=xxx&mobile=133897
POST /api/cycloper/add HTTP/1.1
Host: 192.168.250.128:9090
Content-Type: application/json
Cache-Control: no-cache
{“name”:“xxxx”,“mobile”:“133897”}