expressjs里的请求参数,4.x里只有3种
- req.params
- req.body
- req.query
req.params
app.get('/user/:id', function(req, res){
res.send('user ' + req.params.id);
});
俗点:取带冒号的参数
req.body
var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data
app.post('/', function (req, res) {
console.log(req.body);
res.json(req.body);
})
可以肯定的一点是req.body一定是post请求,express里依赖的中间件必须有bodyParser,不然req.body是没有的。
详细的说明在下面的3种post用法里。
req.query
query是querystring
说明req.query不一定是get
// GET /search?q=tobi+ferret
req.query.q
// => "tobi ferret"//
GET /shoes?order=desc&shoe[color]=blue&shoe[type]=conversereq.query.order
// => "desc"
req.query.shoe.color
// => "blue"
req.query.shoe.type
// => "converse"
因为有变态的写法
// POST /search?q=tobi+ferret
{a:1,b:2}
req.query.q
// => "tobi ferret"
post里看不的,用req.body取。
网友评论