一聚教程网:一个值得你收藏的教程网站

热门教程

node.js如何获取参数 node.js获取参数的方法

时间:2022-06-29 00:41:24 编辑:袖梨 来源:一聚教程网

1、req.body

2、req.query

3、req.params

一、req.body例子

body不是nodejs默认提供的,你需要载入body-parser中间件才可以使用req.body,这个方法通常用来解析POST请求中的数据

 

 代码如下复制代码

 

   

app.post('/test', function(req, res) {

  console.log(req.body.name);

  console.log(req.body.tel);

});

 

 二、req.query例子

有nodejs默认提供,无需载入中间件,这个方法通常用来解析get请求中的数据

 

 代码如下复制代码

GET/test?name=lmw&tel=123456789

  

app.get('/test', function(req, res) {

  console.log(req.query.name);

  console.log(req.query.tel);

});

 

三、req.query和req.body同时使有

 

 代码如下复制代码
 

   

   

   

app.post('/test', function(req, res) {

  console.log(req.query.id);

  console.log(req.body.name);

  console.log(req.body.tel);

});

 

四、req.params

另一种方法传递参数给服务器,但是这不算是传统标准规范的做法,是属于 HTTP Routing 的延伸应用

 

 代码如下复制代码

GET/test/lmw/123456789

  

app.get('/test/:name/:tel', function(req, res) {

  console.log(req.params.name);

  console.log(req.params.tel);

});

 

总结:

req.query:解析后的 url 中的 querystring,如 ?name=haha,req.query 的值为 {name: 'haha'}

req.params:解析 url 中的占位符,如 /:name,访问 /haha,req.params 的值为 {name: 'haha'}

req.body:解析后请求体,需使用相关的模块,如 body-parser,请求体为 {"name": "haha"},则 req.body 为 {name: 'haha'}

以上这篇node.js获取参数的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持本网站。

热门栏目