Install qs
npm install qs --save command to install
1.qs.parse() parses the url into the form of an object
2.qs.stringify() serializes the object into the form of a url, splicing with &
qs.stringify() and The difference between JSON.stringify()
var a = {
name:"小明",
age:20
}
1.qs.stringify序列化结果:
name=小明&age=20
2.JSON.stringify的结果是:
"{"a":"小明","age":20}"
axios请求默认的是application/json:这种格式 {
name:"小明",age:20}
但是有时候后端需要的是表单提交方式,(post请求)post表单请求提交时,使用的是:
content-type就是application/x-www-form-urlencoded,
所以需要将ajax发送请求的application/json改为application/x-www-form-urlencoded
那么content-type就是application/x-www-form-urlencoded
使用qs进行序列化传输的样式是formdata格式的参数 这样的格式:name=xxx&age=xxx
所以采取以下方法:
vue中使用:
1.安装完之后在需要的组件页面引入qs
import qs from 'qs'; //es6语法引入
const qs = require('qs'); //CommonJS语法引入
2. data(){
return {
data:{
uname:'用户1',
pwd:'123456'
}
}
},
methods:{
register(){
//axios请求
//第一种写法
this.$http({
method:'post',
headers:{
'content-type':'application/x-www-form-urlencoded'
},
url:'地址',
data:qs.stringify(this.data),
}).then((res)=>{
console.log(res)
})
},
login(){
//axios请求
第二种写法
this.$http.post('/foo',qs.stringify(this.data)).then((res)=>{
console.log(res)
})
}
}