HTTP協(xié)議 之 Content-Type

完整示例代碼參考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

參考

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容