当前位置: 首页 > 后端技术 > Node.js

express框架中参数注意事项

时间:2023-04-03 23:16:49 Node.js

首发地址:https://clarencep.com/2017/04...转载请注明出处注意:req.params只有参数化路径有参数。查询字符串中的参数应该使用req.query。例如://server.js:app.post('/user/:id',function(req,res){console.log('req.params:',req.params)console.log('req.query:',req.query)console.log('req.body:',req.body)})//HTTP请求:POST/user/123?foo=1&bar=2Content-Type:application/x-www-form-urlencodedaaa=1&bbb=2这样的请求应该使用req.query.foo和req.query.bar获取foo和bar的值,最后打印出来如下:req.params:{id:'123'}req.query:{foo:'1',bar:'2'}req.body:{aaa:'1',bbb:'2'}另外,在req.body上,express框架本身不解析req.body--如果打印出req.body:undefined,说明没有安装解析req.body的插件:为了解析req.body,一般可以安装插件body-parser://假设app是express的实例:constbodyParser=require('body-parser')//在所有路由之前插入这个中间件:app.use(bodyParser.urlencoded())就这样。bodyParser.urlencoded()是HTML中查询字符串形式的默认编码,即application/x-www-form-urlencoded。如果需要解析其他格式,需要添加其他格式的中间件,如:bodyParser.json()支持JSON格式(application/json)bodyParser.raw()会将req.body设置为一个Buffer(Content-Type:application/octet-stream)bodyParser.text()会将req.body设置为Bufferstring(Content-Type:text/plain)但是,bodyParser不支持用于上传文件的multipart/form-data格式,并且需要其他中间件,例如busboy。