本篇文章給大家介紹一下Nodejs獲取參數(shù)的四種方法额划。有一定的參考價(jià)值,有需要的朋友可以參考一下癣猾,希望對(duì)大家有所幫助。
推薦學(xué)習(xí):《nodejs 教程》
獲取請(qǐng)求很中的參數(shù)是每個(gè)web后臺(tái)處理的必經(jīng)之路,nodejs的 express框架 提供了四種方法來實(shí)現(xiàn)离陶。
req.body
req.query
req.params
req.param()
首先介紹第一個(gè)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.
稍微翻譯一下:包含了提交數(shù)據(jù)的鍵值對(duì)在請(qǐng)求的body中,默認(rèn)是underfined,
你可以用body-parser或者multer來解析body
解析body不是nodejs默認(rèn)提供的衅檀,你需要載入body-parser中間件才可以使用req.body
此方法通常用來解析POST請(qǐng)求中的數(shù)據(jù)
第二種是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, {}.
翻譯一下:包含在路由中每個(gè)查詢字符串參數(shù)屬性的對(duì)象招刨。如果沒有,默認(rèn)為{}
有nodejs默認(rèn)提供哀军,無需載入中間件
舉例說明(官方摘抄):
// 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請(qǐng)求沉眶,解析GET里的參數(shù)
第三種是 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 {}.
翻譯:包含映射到指定的路線“參數(shù)”屬性的對(duì)象。
例如杉适,如果你有route/user/:name谎倔,那么“name”屬性可作為req.params.name。
該對(duì)象默認(rèn)為{}猿推。
nodejs默認(rèn)提供片习,無需載入其他中間件
舉例說明
// GET /user/tj
req.params.name
// => "tj"
多適用于restful風(fēng)格url中的參數(shù)的解析
req.query與req.params的區(qū)別
req.params包含路由參數(shù)(在URL的路徑部分),而req.query包含URL的查詢參數(shù)(在URL的蹬叭?后的參數(shù))毯侦。
最后一種req.param()
此方法被棄用,請(qǐng)看官方解釋
Deprecated. Use either req.params, req.body or req.query, as applicable.
翻譯:被棄用具垫,用其他三種方式替換
本文轉(zhuǎn)載自:https://www.php.cn/js-tutorial-475608.html
更多編程相關(guān)知識(shí)侈离,請(qǐng)?jiān)L問:編程視頻!筝蚕!