使用axios post数据时,
需设置header选项的不同情况:
因为axios默认的提交json格式,但后台是表单接收,所以需要设置header
headers:{//上传文件时,文件是通过表单data提交
'Content-type': 'multipart/form-data'
}
headers:{//普通发送数据时
'Content-type': 'application/x-www-form-urlencoded'
}
需修改data选项:
使用qs模块转换数据为字符串连接格式,例如:
data: this.$qs.stringify(senddata)//向后台传输数据时,因后台默认接收表单数据
一份完整的使用post发送数据的示例:
this.$axios({
method: 'post',
url: this.$conf.url+'/kuayu',
data: this.$qs.stringify(senddata),//把json格式的数据stringify
headers:{//修改header头
'Content-type': 'application/x-www-form-urlencoded'
}
})
.then(function (response)
{
console.log(response);
})
.catch(function (error) {
console.log(error);
});
封装一个axios的对象,方便以后调用
import qs from 'qs'
import axios from 'axios'
/* $axios提供2个对外方法
post(url,data,success,errorfun)
get(url,data,success,errorfun)
参数:url : 必须;string;要上传的后台api
参数:data : 必须;object;要发送的数据
参数:success : 必须;function;成功回调
参数:errorfun : 可选;function;失败回调
调用示例:new $axios().post(url,data,success,err);
*/
class $axios {
// post 方法
post(url,data,success,errorfun){
const header = { 'Content-type': 'application/x-www-form-urlencoded' }
const _data = qs.stringify(data);
this._axios('post',url,_data,header,success,errorfun);
}
get(url,data,success,errorfun){
const header = { 'Content-type': 'application/x-www-form-urlencoded' }
this._axios('get',url,data,header,success,errorfun);
}
_axios(method,url,data,header,success,errorfun){
const config = { method: method, url: url, headers:header }
if(method === "post"){
config['data'] = data;
}else{
config['params'] = data;
}
axios(config)
.then(function (response) {
success(response); })
.catch(function (error) {
console.log(error);
console.error("调用axios封装失败,请检查原因。");
if(errorfun){ errorfun(error); }
});
}
}
export {$axios}

本文介绍了axios在POST请求中处理数据的方式,包括设置header适应表单接收,并演示了使用qs模块将数据转换为字符串。此外,还展示了如何封装axios实例以简化后续调用。
567

被折叠的 条评论
为什么被折叠?



