express中url的参数传递和获取

时间:2022-12-03 20:21:52

1,传统get参数

浏览器通过这种形式的url访问localhost/userlist?id=xxx&name=yyy,这种方式可以通过req.query.id获取参数的值

1 router.get('/userlist/', function(req, res, next) {
2     var fs = require("fs");
3     var logstr = JSON.stringify({url:req.path});
4     fs.writeFile('log.txt',logstr,'utf-8',function (err) {
5         !err && console.log('文件写入成功id='+req.query.id+'name='+req.query.name);
6     });
7     var str = req.originalUrl;
8     res.send(str);
9 });

2,占位符传参

这种形式浏览器必须严格按照localhost/userlist/xxx/yyy的形式访问,如果少传一个参数就会报404错误,通过req.params.id获取对应的参数的值

1 router.get('/userlist/:id/:name', function(req, res, next) {
2     var fs = require("fs");
3     var logstr = JSON.stringify({url:req.path});
4     fs.writeFile('log.txt',logstr,'utf-8',function (err) {
5         !err && console.log('文件写入成功id='+req.params.id+'name='+req.params.name);
6     });
7     var str = req.originalUrl;
8     res.send(str);
9 });