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

来源:互联网 发布:知乎如何添加好友 编辑:程序博客网 时间:2024/06/03 19:23

使用vue有一段时间了,下面是我在Java环境下使用vue+axios的时候遇到的一个坑,在这分享给大家,如有不正确或者疑惑的地方可以@我。
邮箱地址:wangpan_java@163.com
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);            })
阅读全文
1 0