基於node.js依賴express解析post請求四種資料格式,node.jsexpress

來源:互聯網
上載者:User

基於node.js依賴express解析post請求四種資料格式,node.jsexpress

node.js依賴express解析post請求四種資料格式

分別是這四種:

  • www-form-urlencoded
  • form-data
  • application/json
  • text/xml

1、www-form-urlencoded

這是http的post請求預設的資料格式,需要body-parser中介軟體的支援

伺服器端的demo:

var express = require('express');var app = express();var bodyParser = require('body-parser');app.use(bodyParser.urlencoded({ extended:true}));app.post('/urlencoded', function(req, res){ console.log(req.body); res.send(" post successfully!");});app.listen(3000);

可以用postman進行測試,這裡就不贅述。

2、form-data

這種方式一般用於資料上傳,需要中介軟體connect-multiparty的支援

伺服器端的demo:

var multipart = require('connect-multiparty');var multipartMiddleware = multipart();app.post('/formdata',multipartMiddleware, function (req, res) {console.log(req.body);res.send("post successfully!");});

3、application/json

body-parser中介軟體支援json解析, 添加中介軟體進行解析即可

app.use(bodyParser.json());

4、text/xml

body-parser預設不支援這種資料格式

解決方案:把請求體參數按照字串讀取出來,然後使用 xml2json 包把字串解析成json對象,然後對json對象進行操作,方便得多。

注意:我們還是要使用 body-parse 得到字串,然後再轉化.

利用req上定義的事件 data 來擷取http請求流, end 事件結束請求流的處理.

利用 xml2json 把上面得到的請求參數流(我們直接轉化為字串)轉化為 json 對象.

demo如下:

var express = require('express');var bodyParser = require('body-parser');var xml2json=require('xml2json');var app = express();app.use(bodyParser.urlencoded({extended: true}));app.post('/xml', function (req, res) {req.rawBody = '';//添加接收變數var json={};req.setEncoding('utf8');req.on('data', function(chunk) { req.rawBody += chunk;});req.on('end', function() {json=xml2json.toJson(req.rawBody);res.send(JSON.stringify(json));}); });app.listen(3000);

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.