Express 路由 参数的获得

req.params

与req.param()方法相比 该属性只能获取 “express路由器传递的参数”, 值得一提的是: 与req.params配合还能在express路由器中玩正则。

示例代码:

1 var express = require('express');
2 var app = express();
3 // 地址栏: localhost:3000/user/app ;
4 app.get('/user/:name', function(req, res){
5 var param = req.params.name;
6 res.send('hello world' + param); // hello world app});


然后看看路由器中神奇的正则使用法,在地址栏输入 localhost:3000/file/javascripts/jquery.js ,

1 var express = require('express');
2 var app = express();
3 // 地址栏:localhost:3000/file/javascripts/jquery.js
4 app.get('/file/*', function(req, res){
5 var param = req.params[0];
6 res.send(param); //javascripts/jquery.js});


ps: 如果没在路由器设置参数, 则 req.params 获得的值为空对象 {}

req.query

 1 示例代码:
 2 var express = require('express');
 3 var app = express();
 4 // 地址栏: localhost:3000/search?q=tobi+ferret
 5 app.get('/search', function(req, res){
 6 var param = req.query.q;res.send(param); 
 7 //tobi ferret});
 8 // 地址栏: localhost:3000/shoes?order=desc&shoe[color]=blue&shoe[type]=converse
 9 app.get('/shoes', function(req, res){
10 var _order = req.query.order;
11 var _color = req.query.shoe.color;
12 var _type = req.query.shoe.type;
13 console.log(_order);// descconsole.log(_color); 
14 // blueconsole.log(_type); // converse
15 res.send('hello world'); });

 

ps: 如果地址栏没传递参数, req.query获得的值也是空对象{}

req.body

该属性主要用与post方法时传递参数使用, 用法最为广泛也最为常见,。需要说明下的是使用该属性时, 得先确认app.js中有没有导入“body-parser”, 该模块在express4.x中已经脱离为独立的模块。

前端代码:

<form method="POST" action="add" name="userform" > 
<input type="text" id="name" name="name" value="xq" class="form-control" /> 
<input type="text" id="age" name="age" value="12" class="form-control" /> 
<input type="text" id="job" name="job" value="coder" class="form-control" /> 
<input type="text" id="hobby" name="hobby" value="run" class="form-control" /> 
<button type="submit" class="btn btn-primary">提交添加</button></form>

 

node代码

 1 var express = require('express');
 2 var router = express.Router();
 3 var bodyParser = require('body-parser');
 4 
 5 var app = express();
 6 
 7 // parse application/x-www-form-urlencoded 
 8 app.use(bodyParser.urlencoded({ extended: false }));
 9 // parse application/json 
10 app.use(bodyParser.json());
11 app.post('/add',urlencodedParser,(function(req, res){
12 var userObj = {};
13 userObj = {
14 name: req.body.name,
15 age: req.body.age,
16 job: req.body.job,
17 hobby:req.body.hobby
18 })
19 console.log(userObj);
20 // {name:'xq',age:'12',job:'coder',hobby:'run'}});


当然,以上都没有涉及文件传输,post方式涉及文件传输需要使用formidable、multer等插件包

posted @ 2019-04-20 17:26  我爱吃小丸子  阅读(540)  评论(0编辑  收藏  举报