vue axios使用form-data的形式提交数据
vue axios request payload form data
因为axios默认发送数据时,数据格式是Request Payload,而并不是咱们经常使用的Form Data格式,PHP后端未必能正常获取到,因此在发送以前,须要使用qs模块对其进行处理。php
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';前端
axios请求不携带cookie
this.axios.defaults.withCredentials = true;// 跨域携带cookie
在跨域的状况下不只前端要设置withCredentials,后端也是要设置Access-Control-Allow-Credentials的。vue
=================
表单提交数据是名值对的方式,且Content-Type为application/x-www-form-urlencoded,而文件上传服务器须要特殊处理,普通的post请求(Content-Type不是application/x-www-form-urlencoded)数据格式不固定,不必定是名值对的方式,因此服务器没法知道具体的处理方式,因此只能经过获取原始数据流的方式来进行解析。jquery
jquery在执行post请求时,会设置Content-Type为application/x-www-form-urlencoded,因此服务器可以正确解析,而使用原生ajax请求时,若是不显示的设置Content-Type,那么默认是text/plain,这时服务器就不知道怎么解析数据了,因此才只能经过获取原始数据流的方式来进行解析请求数据。ios
=================
axios.post('post.php', {
a: '1'
}).then(function(response) {
alert(response.data);
}).catch(function(error) {
alert(error);
});
因为axios默认发送数据时,数据格式是Request Payload,而并不是咱们经常使用的Form Data格式,PHP后端未必能正常获取到,因此在发送以前,须要使用qs模块对其进行处理。ajax
import qs from 'qs';
...
axios.post('post.php', qs.stringify({
a: '1'
}))
.then( ... )
.catch( ... );
======================
经过this.$http去调用axios,若是以前你的vue-resourse也是这么写的话,能够无缝切换。换成this.axios也是没有问题的。axios
在入口文件main.js修改:
import qs from 'qs'后端
#建立一个axios实例
var axios_instance = axios.create({
#config里面有这个transformRquest,这个选项会在发送参数前进行处理。
#这时候咱们经过qs.stringify转换为表单查询参数
transformRequest: [function (data) {
data = qs.stringify(data);
return data;
}],
#设置Content-Type
headers:{'Content-Type':'application/x-www-form-urlencoded'}
})
Vue.use(VueAxios, axios_instance)跨域
之后发起http请求,以下便可:
var vm = this
this.$http.post(vm.url,data).then((response)=>{
alert(response.data.msg);
})服务器
======================let postData = this.$qs.stringify({ key1:value1, key2:value2, key3:value3,});this.$axios({ method: 'post', url:'url', data:postData}).then((res)=>{ });====================上传文件var fd = new FormData()fd.append('file', files[0])let config = { headers: { 'Content-Type': 'multipart/form-data' }}axios.post(that.uploadUrl, fd,config).then( res => { console.log(res)}).catch( res => { console.log(res)})====================