nodeJS 取参 -- req.body & req.query & req.params

原链接:http://www.cnblogs.com/ostrich-sunshine/p/6741180.html

获取请求中的参数是每个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.
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.
翻译:被弃用,用其他三种方式替换

转载于:https://www.cnblogs.com/lyls/p/7486986.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值