原鏈接:http://www.cnblogs.com/ostrich-sunshine/p/6741180.html
獲取請求中的參數是每個web后台處理的必經之路,nodejs的 express框架 提供了四種方法來實現。
-
req.body
-
req.query
-
req.params
-
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.
1
|
<span style=
"font-size: 14px"
><code
class
=
"hljs sql"
><span
class
=
"hljs-keyword"
><span
class
=
"hljs-keyword"
><span
class
=
"hljs-keyword"
><span
class
=
"hljs-keyword"
><span
class
=
"hljs-keyword"
><span style=
"color: #008000"
>稍微翻譯一下</span>:包含了提交數據的鍵值對在請求的 <span
class
=
"hljs-keyword"
>body 中,默認是 underfined,<br></span></span></span></span></span></span></code></span>
|
1
|
<span style=
"font-size: 14px"
><code
class
=
"hljs sql"
><span
class
=
"hljs-keyword"
><span
class
=
"hljs-keyword"
><span
class
=
"hljs-keyword"
><span
class
=
"hljs-keyword"
><span
class
=
"hljs-keyword"
><span
class
=
"hljs-keyword"
> 你可以用 <span
class
=
"hljs-keyword"
>body-parser 或者 multer 來解析 <span
class
=
"hljs-keyword"
>body</span></span></span></span></span></span></span></span></code></span>
|
解析 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中的參數的解析
req.query與req.params的區別
req.params包含路由參數(在URL的路徑部分),而req.query包含URL的查詢參數(在URL的?后的參數)
最后一種req.param()
此方法被棄用,請看官方解釋
Deprecated. Use either req.params, req.body or req.query, as applicable. 翻譯:被棄用,用其他三種方式替換