方案一:
在config.index.js中设置webpack
最初的方案是前台传JSON格式的数据过去;设置’Content-Type’:
'application/json;charset=UTF-8',大概:
axios.post('/user',JSON.stringify(params),{
headers: {
'Content-Type': 'application/json;charset=UTF-8'
}
})
.then(function (res) {
console.log(res);
})
.catch(function (error) {
console.log(error);
});
并且后台改变其接收参数的方式改为@RequestBody。
此方法主要参考该博客:https://blog.csdn.net/CarryBest/article/details/80079364
该博客有个问题,就是接收单个参数的时候,是可行的,但是要是接收多个参数,仍然会报错。解决方法是只要后台设置接收的参数为Map类型或是多个参数组成的类的这种类型
方案二
使用URLSearchParams的API:
const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
但是该API的浏览器兼容性不是很理想,不过有polyfill,提供了兼容性方案。(https://github.com/WebReflection/url-search-params )
代码
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: ' http://172.17.186.222:8999/',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
},
methods: {
login(forName) {
this.$refs[forName].validate(valid => {
if (valid) {
this.$axios.post('api/user/login',{
name:this.loginForm.username,
password:this.loginForm.password,
},
{ headers: { 'Content-Type': 'application/json' }
}
).then(res=>{
if(res.data.code===0){
Cookies.set("userName",res.data.data.username);
this.userName=res.data.data.username;
this.$router.push("/index/statistics");
}else if(res.data.code ===50010){
this.$message.closeAll();
this.$message({
duration: 1600,
message: "用户名或密码错误!",
type: "error"
});
}
else{
this.$message.closeAll();
this.$message({
message: res.data.msg,
type: "error"
});
}
})
} else {
console.log("error submit!!");
return false;
}
});
}
}
参考