nodejs取参四种方法req.body,req.params,req.param,req.body

释放双眼,带上耳机,听听看~!

2019独角兽企业重金招聘Python工程师标准>>> nodejs取参四种方法req.body,req.params,req.param,req.body

获取请求很中的参数是每个web后台处理的必经之路,nodejs的 **express框架 **提供了四种方法来实现。

req.body

req.query

req.params

req.param()

首先介绍第一个req.body


1
2
3
4
5
6
7
1官方文档解释:
2Contains 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
7

解析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

 


1
2
3
4
5
6
7
8
9
1官方文档:
2An object containing properties mapped to the named route “parameters”. 
3For example, if you have the route /user/:name, 
4then the “name” property is available as req.params.name. This object defaults to {}.
5
6翻译:包含映射到指定的路线“参数”属性的对象。
7例如,如果你有route/user/:name,那么“name”属性可作为req.params.name。
8该对象默认为{}。
9

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://my.oschina.net/u/2519530/blog/535309

给TA打赏
共{{data.count}}人
人已打赏
安全技术

对称加密与非对称加密优缺点详解

2021-8-18 16:36:11

安全技术

C++ 高性能服务器网络框架设计细节

2022-1-11 12:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索