完整示例代码参考Content-Type
目录
application/x-www-form-urlencoded
cnpm i -g express nodemon
# mkdir Content-Type && cd Content-Type
express -e form-urlencoded
# cd form-urlencoded
cnpm i
vim routes/index.js
var express = require('express');
var router = express.Router();
router.post('/', function (req, res, next) {
res.send(req.body);
});
module.exports = router;
- 测试
nodemon
关于nodemon 更多参考nodemon
curl -X POST -d 'name=木木&id=yl33643' localhost:3000 | json
{
"name": "木木",
"id": "yl33643"
}
application/x-www-form-urlencoded是浏览器表单和curl的默认编码方式
- 抓包
http-content-type-01.png
这里使用Wireshark抓包工具 更多参考 Wireshark - 过滤器
multipart/form-data
express -e form-data
# cd form-data
cnpm i
cnpm i --save connect-multiparty
关于connect-multiparty 更多参考connect-multiparty
vim routes/index.js
var express = require('express');
var multipart = require('connect-multiparty');
var router = express.Router();
router.post('/', multipart(), function (req, res, next) {
res.send(req.body);
});
module.exports = router;
- 测试
nodemon
curl -X POST -F 'name=木木' -F 'id=yl33643' localhost:3000 | json
{
"name": "木木",
"id": "yl33643"
}
- 抓包
http-content-type-02.png
相比application/x-www-form-urlencoded multipart/form-data不仅可以上传键值对还可以上传文件
application/json
express -e json
# cd json
cnpm i
vim routes/index.js
var express = require('express');
var router = express.Router();
router.post('/', function (req, res, next) {
res.send(req.body);
});
module.exports = router;
- 测试
nodemon
curl -X POST -H 'Content-Type:application/json' -d '{"name":"木木","id":"yl33643"}' localhost:3000 | json
{
"name": "木木",
"id": "yl33643"
}
- 抓包
http-content-type-03.png