express 框架中的参数小记
首發(fā)地址:https://clarencep.com/2017/04...
轉載請注明出處
注意:req.params 只有在參數化的路徑中的參數。查詢字符串中的參數要用 req.query.
比如:
// server.js: app.post('/user/:id', function(req, res){console.log('req.params: ', req.params)console.log('req.query: ', req.query)console.log('req.body: ', req.body) }) // HTTP request: POST /user/123?foo=1&bar=2 Content-Type: application/x-www-form-urlencodedaaa=1&bbb=2這樣的請求,應該是要用 req.query.foo 和 req.query.bar 來獲取 foo 和 bar 的值,最終打印出如下:
req.params: { id: '123' } req.query: { foo: '1', bar: '2' } req.body: { aaa: '1', bbb: '2' }關于 req.body
此外,express 框架本身是沒有解析 req.body 的 -- 如果打印出來 req.body: undefined則說明沒有安裝解析 req.body 的插件:
為了解析 req.body 一般可以安裝 body-parser 這個插件:
// 假設 `app` 是 `express` 的實例:const bodyParser = require('body-parser')// 在所有路由前插入這個中間件:app.use(bodyParser.urlencoded())這樣就可以了。
bodyParser.urlencoded()是HTML中默認的查詢字符串形式的編碼,即application/x-www-form-urlencoded. 如果需要解析其他格式的,則需要分別加入其他格式的中間件,比如:
bodyParser.json() 支持JSON格式(application/json)
bodyParser.raw() 將會把 req.body 置為一個 Buffer (Content-Type:application/octet-stream)
bodyParser.text() 將會把 req.body 置為一個 string (Content-Type: text/plain)
然而上傳文件用的 multipart/form-data 格式卻沒有被 bodyParser 所支持,需要使用 busboy 之類的其他中間件。
總結
以上是生活随笔為你收集整理的express 框架中的参数小记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 运维基础--Linux用户和组的管理
- 下一篇: linux定时脚本任务