700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > nodejs express如何接收POST传递的参数

nodejs express如何接收POST传递的参数

时间:2019-11-10 00:18:23

相关推荐

nodejs express如何接收POST传递的参数

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”}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。