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


摘要: nodejs取參四種方法req.body,req.params,req.param,req.body 獲取請求很中的參數是每個web后台處理的必經之路,nodejs提供了四種方法來實現。

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

  1. req.body

  2. req.query

  3. req.params

  4. req.param()

首先介紹第一個req.body

  1.  
    官方文檔解釋:
  2.  
    Contains key-value pairs of data submitted in the request body. By default, it is undefined,
  3.  
     and is populated when you use body-parsing middleware such as body-parser and multer.
  4.  
     
  5.  
    稍微翻譯一下:包含了提交數據的鍵值對在請求的body中,默認是underfined,
  6.  
    你可以用body-parser或者multer來解析body

解析body不是nodejs默認提供的,你需要載入body-parser中間件才可以使用req.body

此方法通常用來解析POST請求中的數據

第二種是req.query

  1.  
    官方文檔解釋:
  2.  
    An  object containing a property for each query string parameter in the route. 
  3.  
    If there  is no query string, it is the empty object, {}.
  4.  
    翻譯一下:包含在路由中每個查詢字符串參數屬性的對象。如果沒有,默認為{}

有nodejs默認提供,無需載入中間件

舉例說明(官方摘抄):

  1.  
    // GET /search?q=tobi+ferret
  2.  
    req.query.q
  3.  
    // => "tobi ferret"
  4.  
     
  5.  
    // GET /shoes?order=desc&shoe[color]=blue&shoe[type]=converse
  6.  
    req.query.order
  7.  
    // => "desc"
  8.  
    req.query.shoe.color
  9.  
    // => "blue"
  10.  
    req.query.shoe.type
  11.  
    // => "converse"

此方法多適用於GET請求,解析GET里的參數

第三種是 req.params

 

  1.  
    官方文檔:
  2.  
    An object containing properties mapped to the named route “parameters”. 
  3.  
    For example, if you have the route /user/:name, 
  4.  
    then the “name” property is available as req.params.name. This object defaults to {}.
  5.  
     
  6.  
    翻譯:包含映射到指定的路線“參數”屬性的對象。
  7.  
    例如,如果你有route/user/:name,那么“name”屬性可作為req.params.name。
  8.  
    該對象默認為{}。

nodejs默認提供,無需載入其他中間件

舉例說明

  1.  
    // GET /user/tj
  2.  
    req. params.name
  3.  
    // => "tj"

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

req.query與req.params的區別

req.params包含路由參數(在URL的路徑部分),而req.query包含URL的查詢參數(在URL的?后的參數)。

最后一種req.param()

此方法被棄用,請看官方解釋

  1.  
    Deprecated. Use either req.params, req.body or req.query, as applicable.
  2.  
    翻譯:被棄用,用其他三種方式替換

 

 

 

取得 GET Request 的 Query Strings:

  1.  
    GET /test?name=fred&tel=0926xxx572
  2.  
     
  3.  
    app .get('/test', function(req, res) {
  4.  
    console.log(req.query.name);
  5.  
    console.log(req.query.tel);
  6.  
    });

如果是表單且是用 POST method:

  1.  
    <form action='/test' method='post'>
  2.  
    <input type='text' name='name' value='fred'>
  3.  
    <input type='text' name='tel' value='0926xxx572'>
  4.  
    <input type='submit' value='Submit'>
  5.  
    </form>
  6.  
    app.post( '/test', function(req, res) {
  7.  
    console.log(req.query.id);
  8.  
    console.log(req.body.name);
  9.  
    console.log(req.body.tel);
  10.  
    });

當然也可以 Query Strings 和 POST method 的表單同時使用:

  1.  
    <form action='/test?id=3' method='post'>
  2.  
    <input type='text' name='name' value='fred'>
  3.  
    <input type='text' name='tel' value='0926xxx572'>
  4.  
    <input type='submit' value='Submit'>
  5.  
    </form>
  6.  
    app.post( '/test', function(req, res) {
  7.  
    console.log(req.query.id);
  8.  
    console.log(req.body.name);
  9.  
    console.log(req.body.tel);
  10.  
    });

順帶補充,還有另一種方法傳遞參數給 Server,就是使用路徑的方式,可以利用 Web Server 的 HTTP Routing 來解析,常見於各種 Web Framework。這不算是傳統標准規范的做法,是屬於 HTTP Routing 的延伸應用。

  1.  
    GET /hello/fred/0926xxx572
  2.  
     
  3.  
    app .get('/hello/:name/:tel', function(req, res) {
  4.  
    console.log(req.params.name);
  5.  
    console.log(req.params.tel);
  6.  
    });

來源:http://liuxufei.com/blog/jishu/798.html

params和data的區別,即get和post請求的區別,HTTP協議的基礎知識

get請求參數是帶在url上的,必須使用params

post請求是body data使用data

假設url:http://192.168.1.111:8080/api/cluster/group?wzd=111&abc=cc
方法類型:POST,body是{"name":"abc"}
 
1. request.query
得到一個bottle的FormsDict對象,該對象可以轉化為字典,里面的內容是:
{"wzd":"111","abc":"cc"},即,是url中后面的參數
 
2.request.params
也是得到FormsDict對象,轉化為字典后,其內容是:
{"wzd":"111","abc":"cc","{"name":"abc"}":""}
即,其內容包含了url后的參數和值,同時也包含了body中的值,要注意的是,它把body中所以的參數作為一個key存入了。
 
3.request.body
返回一個StringIO對象,通過read方法取出的數據是body里的所有值,不管body里是不是json該方法都原樣返回body里的所有內容。對本例而言是返回:{"name":"abc"}
 
4.request.query_string
它得到的是,url中?后面所有的值,最為一個字符串,即:wzd=111&abc=cc
 
5.request.json
當請求的Content-Type`` 是`application/json的時候,該方法返回的是body中的json串,如果body中不是json會拋出異常:ValueError: No JSON object could be decoded,對應本例,返回:{"name":"abc"}
 
6.request.form
有這么一個表單:
1
2
3
4
5
< form action="/login" method="post">
Username: < input name="username1" type="text" />
Password: < input name="password1" type="password" />
< input value="Login" type="submit">
</ form >
那么要獲取username/password有如下方法:
方法一:
username = request.forms.get('username1') # 對應的是Username輸入框中的name屬性
password = request.forms.get('password1') # 對應的是password輸入框中的name屬性
方法二:
username = request.POST.get('username')
password = request.POST.get('password')
並且,上面兩種get方法都可以跟一個默認值,當username或者password不存在的時候返回設置的默認值,如:username = request.POST.get('username','abc'),當username不存在的時候,返回abc,如果不設置,返回none
 
另外,bottle.request.forms,返回表單中所有的k,v,即:{“username”:"123","password":"324"}

body:請求體中的數據

query:請求的參數,URL后面以?的形式,例:user?id

params:請求的參數,URL后面以/的形式,例:user/:id


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM