req.paramsjavascript
與req.param()方法相比 該屬性只能獲取 「express路由器傳遞的參數」, 值得一提的是: 與req.params配合還能在express路由器中玩正則。前端
示例代碼:java
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 ,node
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 得到的值爲空對象 {}jquery
req.queryexpress
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得到的值也是空對象{}json
req.bodyapp
該屬性主要用與post方法時傳遞參數使用, 用法最爲普遍也最爲常見,。須要說明下的是使用該屬性時, 得先確認app.js中有沒有導入「body-parser」, 該模塊在express4.x中已經脫離爲獨立的模塊。post
前端代碼:ui
<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等插件包