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

Logo

前往低代码交流专区

更多推荐