java使用axios.js的post请求后台时无法接收到参数的问题

1.在使用异步请求后台时,由于官方不在更新vue-resource,推荐使用axios,因此在使用的时候难免会遇到各种问题。目前遇到最大的问题是在使用axios.post的请求向Java后端传入入参时,后端无法接收到参数。在这里主要处理移动端浏览器兼容的问题。
在这里我提供了两种解决办法:
一、URLSearchParams.append()方法
由于URLSearchParams接口在各个浏览器兼容性问题,这种方法在PC端绝大多数浏览器是OK的,但是在手机端正相反,基本上都不支持。

getBarCode : _ => {
let param = new URLSearchParams();
param.append(“userName”,”admin”);
param.append(“userPassword”,”admin”);
axios.post(“/index.html”,param)
.then(function(response){
console.log(response);
})
.catch(function(response){
console.log(response)
})
}
二、主要解决移动端浏览器兼容性问题

//请求后台数据之前转换入参
transformRequest: function (data) {
let ret = ”
for (let it in data) {
ret += encodeURIComponent(it) + ‘=’ + encodeURIComponent(data[it]) + ‘&’
}
return ret
}

axios.post(url,this.transformRequest(param),{
headers: {
‘Content-Type’: ‘application/x-www-form-urlencoded;charset=utf-8’
}
}).then(function(res){
console.log(res);
}).catch(function(res){
console.log(res);
})

三、spring mvc通过RequestBody 接受参数,不能用@RequestParam

@RequestMappting(“/api/doLogin”)
@ResponseBody
public Object doLogin(@RequestBody Map map) throws Exception {
System.out.println(“username: “+map.get(“username”));
System.out.println(“password: “+map.get(“password”));
JSONObject json = new JSONObject();
json.put(“success”, true);
return json;
}

超赞:
http://www.jianshu.com/p/042632dec9fb

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值