总提要:首先他们都是用于在Express中获取request请求的参数
区别:
1.req.query
由nodejs默认提供,无需载入中间件,此方法多适用于GET请求,解析GET请求中的参数。
router.get('/login',function(req,res){
console.log(req.query)
})
开启服务 可以得到:
{username:'iwen',password:'123'}
2.req.params
nodejs默认提供,无需载入其他中间件。req.params包含路由参数,而req.query包含URL的查询参数(在URL的?后的参数)
先说个简单的例子: 如果你有route/user.:id 那么'id' 属性就是req.params.id
ps:路由参数:通俗来说就是在路由跳转时,有时需要从本页面带一些参数去目标页面,来实现一些想实现的效果。
app.get('/test/:id',function(req,res){
console.log(req.params)
})
此时控制台会打印:
{id:123}
附上vue中跳转到音乐界面的前台跳转代码:
(1) 在路由实例中(与上述无关):
{
path:'/music/post/:id',
name:'music',
component:Music
}
(2) 在App.vue中:
<router-link :to="{ name:'music',params:{id:'1001'}}">音乐</router-link>
(3) 在Music.vue中:
<div>{{ this.$route.params.id==='1001' ? '麻雀' : '珊瑚海'}}</div>
以上是前台和node后台对 params 的应用
3.req.body
req.body与上述两者不同,它通常用来解析POST请求中的数据,并且req.body不是nodejs默认提供的,需要载入中间件body-parser中间件才可以使用req.body。
(1) 此时我们在node的express框架中需要先引入:
const bodyParser = require("body-parser");
(2) 接着引入post请求获取参数的方案:
app.use(bodyParser.urlencoded({
extended: true
}));
(3) 请求代码:
router.post('/login',function(req,res){
let username=req.body.username;
let password=req.body.password;
if(username && password){
res.send({
code:200,
username:username,
token:'dhuadh123hui213h,dqwdfiuejnfuiwjf,fewkio0kjfi9203kjirjf'
})
}else{
code:500,
res.send({
msg:'用户名密码错误'
})
}
})