1.背景
项目中前端一直使用jQuery+EasyUI,在使用ajax请求时默认发送的是FormData请求,即在后台可以直接使用request.getParameter方法获取请求参数,近期项目中引用了Vue,ajax请求使用了axios,但在使用过程中发现axios在使用post方法请求时,默认发送的数据是Json格式的文本,后台使用request.getParameter不能获取到提交的参数值,所以需要对axios进行配置,将请求时的Json格式的数据转为FormData数据
axios.post('/sbjk/index_loginJson.action', {username:this.username, password:this.password})
.then((res)=>{
console.log(res.data)
}, (err)=>{
console.log(err);
});
2.使用axios拦截器处理请求参数
axios.interceptors.request.use(
config => {
if(config.data && config.data.constructor!=FormData){
var data = new FormData();
for(var key in config.data){
var val = config.data[key];
if(val===null || val===undefined){
data.append(key, '');
}
else if(val.constructor==Array){
for(var i=0;i<val.length;i++){
data.append(key, typeof(val[i])=='object'?JSON.stringify(val[i]):val[i]);
}
}
else{
data.append(key, typeof(val)=='object'?JSON.stringify(val):val);
}
}
config.data = data;
}
return config;
},
error => Promise.error(error))
经过拦截器处理后,提交的参数变成FormData,后台就可以正常获取参数了