完整示例代碼參考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
關(guān)于nodemon 更多參考nodemon
curl -X POST -d 'name=木木&id=yl33643' localhost:3000 | json
{
"name": "木木",
"id": "yl33643"
}
application/x-www-form-urlencoded是瀏覽器表單和curl的默認(rèn)編碼方式
- 抓包

http-content-type-01.png
這里使用Wireshark抓包工具 更多參考 Wireshark - 過濾器
multipart/form-data
express -e form-data
# cd form-data
cnpm i
cnpm i --save connect-multiparty
關(guān)于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