axios 学习笔记之context-type与 'application/x-www-form-urlencoded'
解决axios默认context-type是json问题
1.引入了Qs,并添加 header的情况。结果请求中header 中的contex-type为application/x-www-form-urlencoded
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
<script>
//局部引入才可以,为什么?
import Qs from 'qs'
export default {
data() {
......
},
methods: {
submitForm(formName) {
let that = this;
this.$refs[formName].validate((valid) => {
if (valid) {
let request = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'post',
url: "http://127.0.0.1:18080/login",
data: Qs.stringify({
name: that.$data.ruleForm.name,
pass: that.$data.ruleForm.pass
})
}
this.axios.post(request.url, request.data, request.headers).then(function(response) {
alert(response.data)
});
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
}
}
}
</script>
2.引入header参数,没有引入qs,使用手动拼参参数的形式。结果请求中header 中的contex-type为application/x-www-form-urlencoded
data: 'name=' + that.$data.ruleForm.name + '&pass=' + that.$data.ruleForm.pass
methods: {
submitForm(formName) {
let that = this;
this.$refs[formName].validate((valid) => {
if (valid) {
let request = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'post',
url: "http://127.0.0.1:18080/login",
data: 'name=' + that.$data.ruleForm.name + '&pass=' + that.$data.ruleForm.pass
}
this.axios.post(request.url, request.data, request.headers).then(function(response) {
alert(response.data)
});
} else {
console.log('error submit!!');
return false;
}
});
},
3.没有headers ,没有qs 。data使用手动拼接参数。结果请求中header 中的contex-type为application/x-www-form-urlencoded
submitForm(formName) {
let that = this;
this.$refs[formName].validate((valid) => {
if (valid) {
let request = {
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded'
// },
method: 'post',
url: "http://127.0.0.1:18080/login",
data: 'name=' + that.$data.ruleForm.name + '&pass=' + that.$data.ruleForm.pass
}
this.axios.post(request.url, request.data, request.headers).then(function(response) {
alert(response.data)
});
} else {
console.log('error submit!!');
return false;
}
});
},
- 随便设置一个 context-type 使用qs格式化。结果请求中header 中的contex-type为application/x-www-form-urlencoded
submitForm(formName) {
let that = this;
this.$refs[formName].validate((valid) => {
if (valid) {
let request = {
headers: {
'Content-Type': 'text/xml'
},
method: 'post',
url: "http://127.0.0.1:18080/login",
data: Qs.stringify({
name: that.$data.ruleForm.name,
pass: that.$data.ruleForm.pass
})
}
this.axios.post(request.url, request.data, request.headers).then(function(response) {
alert(response.data)
});
} else {
console.log('error submit!!');
return false;
}
});
},
总结:根绝以上实验推测,axios的的context-type,和data的数据类型有很大关系,和header中context-type关系不大。这个是很诡异的一个地方。特此记录。