在Express中獲取表單GET請求引數
Express內置了一個API,可以直接通過req.query來獲取
req.query
在Express中獲取表單POST請求體資料
在Express中沒有內置獲取表單POST請求體的API,這里我們需要使用一個第三方包:body-parser
安裝:
npm install --save body-parser
配置:
var express = require('express')
//0.引包
var bodyParser = require('body-parser')
var app = express()
//配置 body-parser
//只要加入這個配置,則在 req 請求物件上會多出來一個屬性 :body
//也就是說你就可以直接通過 req.body 來獲取表單 POST 請求體資料了
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
使用:
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
//可以通過 req.body 獲取表單資料
res.end(JSON.stringify(req.body, null, 2))
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/172773.html
標籤:其他
