分享好友 编程语言首页 频道列表

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

nodejs文章/教程  2023-02-09 10:140
摘要: 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

摘要: 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

查看更多关于【nodejs文章/教程】的文章

展开全文
相关推荐
反对 0
举报 0
评论 0
图文资讯
热门推荐
优选好物
更多热点专题
更多推荐文章
打造自己的 nodejs 静态文件服务器(帖子内容,直接复制别人的)
用NodeJS打造你的静态文件服务器在《The Node Beginner Book》的中文版(http://nodebeginner.org/index-zh-cn.html)发布之后,获得国内的好评。也有同学觉得这本书略薄,没有包含进阶式的例子。@otakustay同学说:“确实,我的想法是在这之上补一个简单的MV

0评论2023-02-10548

NodeJS无所不能:细数10个令人惊讶的NodeJS开源项目
在几年的时间里,NodeJS逐渐发展成一个成熟的开发平台,吸引了许多开发者。有许多大型高流量网站都采用NodeJS进行开发,像PayPal,此外,开发人员还可以使用它来开发一些快速移动Web框架。  除了Web应用外,NodeJS也被应用在许多方面,本文盘点了NodeJS在其

0评论2023-02-10598

Linux环境下的Nodejs linux安装基本环境
最近在学习Node.js,在window下总是觉得不那么爽快。最简单而且环保的方法是在虚拟机中安装一个Linux。 { 1.Linux:家中的Linux为Centos。 2.VirtuallyBox: 开启2块网卡。第一个选Host-Only目的是为了让虚拟机通上网。第二块选Bridge Adapter,这是为了

0评论2023-02-09597

nodejs package.json说明
{"name": "test", //项目名称(必须),由小写英文字母、数字和下划线,不能含空格"version": "1.0.0", //项目版本(必须)"description": "This is for study gulp project !", //项目描述(必须)"homepage": "", //项目主页url " key

0评论2023-02-09473

nodejs查看本机hosts文件域名对应ip
const dns = require('dns')dns.lookup('domainName', function(err, result) {console.log(result)}) related:https://***.com/questions/36689536/how-to-resolve-hostname-to-an-ip-address-in-node-js

0评论2023-02-09475

nodejs工程拷贝后运行报module找不到问题
工程文件夹通过复制黏贴到另外一个地方,运行后报错 “can`t find module 某某某”,查看原因:输入node 进入控制台,输入console.log(module.paths)查看当前nodejs查找module的路径,如果没有工程里的node_modules,通过module.paths.push加入,检查是否有效

0评论2023-02-09947

C# Socket TCP Server & Client & nodejs client cctv5体育节目表
要调试公司某项目里的一个功能,因为要准备测试环境,趁这个机会重温了一下Socket(全还给老师了 -_-#),做个备份。C# Serverstatic void Main(string[] args){int port = 81;string host = "192.168.1.151";//创建终结点IPAddress ip = IPAddress.Parse(hos

0评论2023-02-09810

nodejs微信公众号快速开发|自定义关键字回复
一点说明:nodejs 微信api 扩展,集成大部分功能。案例https://github.com/leiroc/node-wxeasy-example 上传example中文件到服务器 ,然后 npm install 成功https://github.com/leiroc/node-wxeasy-exampleBUG and NEWS增加客户功能增加模板消息增加扫描带参数

0评论2023-02-09404

Centos 32位 安装 NodeJS
yum -y install gcc make gcc-c++ openssl-devel wget下载源码及解压:wget https://nodejs.org/dist/v6.9.5/node-v6.9.5.tar.gztar -zvxf node-v0.10.26.tar.gz编译及安装:cd node-v0.10.26 切换目录,执行./configuremakemake install验证是否安装配置成功

0评论2023-02-09537

nodejs一部分基本模块及作用 node 引入一个模块的过程是什么
收集了NodeJS开发中常用的一些模块。MVC框架 -ExpressExpress 是轻量灵活的Nodejs Web应用框架,它可以快速地搭建网站。Express框架建立在Nodejs内置的Http模块上,并对Http模块再包装,从而实际Web请求处理的功能。它支持多种前端模板,如Jade, EJS等。它是T

0评论2023-02-09868

nodejs定时启动程序 nodejs开机自启
npm install node-schedule# 或yarn add node-schedule使用(second、minute、hour、  date、dayOfWeek、month、year)每分钟第1秒执行一次const schedule = require("node-schedule");var rule = new schedule.RecurrenceRule();rule.second = 1;// 秒schedu

0评论2023-02-09406

nodejs学习:师哥自家的twenty博客框架
这周继续为DTree项目预热,学习sails框架的搭建和结构熟悉。正好师哥在做一个nodejs的CMS框架twenty,他们用的就是sails框架。结构首先简单了解一下结构。在jade文件里由angularjs的控制器进行数据的传递,然后传到一个个modules里面进行操作。路由跳转则不用

0评论2023-02-09486

更多推荐