1. 程式人生 > >node.js取參四種方法req.body,req.params,req.param,req.body

node.js取參四種方法req.body,req.params,req.param,req.body

node.js取參四種方法req.body,req.params,req.param,req.body

參考:https://my.oschina.net/u/2519530/blog/535309

獲取請求很中的引數是每個web後臺處理的必經之路,nodejs的 express框架 提供了四種方法來實現。

1,req.body

2,req.query

3,req.params

4,req.param()

首先介紹第一個req.body

複製程式碼

官方文件解釋:
Contains key-value pairs of data submitted in the request body. By default, it is undefined,
 and is populated when you use body-parsing middleware such as body-parser and multer.

稍微翻譯一下:包含了提交資料的鍵值對在請求的body中,預設是underfined,
你可以用body-parser或者multer來解析body

複製程式碼

解析body不是nodejs預設提供的,你需要載入body-parser中介軟體才可以使用req.body;

此方法通常用來解析POST請求中的資料

第二種是req.query

官方文件解釋:
An object containing a property for each query string parameter in the route. 
If there is no query string, it is the empty object, {}.
翻譯一下:包含在路由中每個查詢字串引數屬性的物件。如果沒有,預設為{}

有nodejs預設提供,無需載入中介軟體

舉例說明(官方摘錄)

複製程式碼

// GET /search?q=tobi+ferret
req.query.q
// => "tobi ferret"

// GET /shoes?order=desc&shoe[color]=blue&shoe[type]=converse
req.query.order
// => "desc"
req.query.shoe.color
// => "blue"
req.query.shoe.type
// => "converse"

複製程式碼

注意:此方法多適用於GET請求,解析GET裡的引數

第三種是 req.params

複製程式碼

官方文件:
An object containing properties mapped to the named route “parameters”. 
For example, if you have the route /user/:name, 
then the “name” property is available as req.params.name. This object defaults to {}.

翻譯:包含對映到指定的路線“引數”屬性的物件。
例如,如果你有route/user/:name,那麼“name”屬性可作為req.params.name。
該物件預設為{}。

複製程式碼

nodejs預設提供,無需載入其他中介軟體

舉例說明

// GET /user/tj
req.params.name
// => "tj"

多適用於restful風格url中的引數的解析

 

eq.query與req.params的區別
req.params包含路由引數(在URL的路徑部分),而req.query包含URL的查詢引數(在URL的?後的引數)。

 

最後一種req.param()

已經被官方棄用,用前三種方法替代

官方連結:http://www.expressjs.com.cn/4x/api.html#req.param