Loading... # 引言 写完接口后通过PostMan测试过接口,可以正常请求,但是项目的前端是Vue写的,使用的Axios,说请求不到数据,随后添加了toString方法,打包部署,发现后端确实无法接收到参数,但是PostMan可以呀,所以排除了接口问题,所以对前端进行梳理。 # 接口的Demo ## Controller ```java @RestController public class bug { @PostMapping("/test") public String demo (MyEntity entity){ return entity.toString(); } } ``` ## Entity ```java @Data @AllArgsConstructor @NoArgsConstructor @ToString public class MyEntity { private Integer id; private String name; private String sex; } ``` # 前端 ## Axios 原方法 ```javascript axios({ method: 'post', url: 'http://127.0.0.1:8080/test', data: {"id": this.id, "name": this.name, "sex": this.sex}, }).then(res => { this.rst = res.data }) ``` ## Axios 新方法 ```javascript axios({ method: 'post', url: 'http://127.0.0.1:8080/test', data: {"id": this.id, "name": this.name, "sex": this.sex},transformRequest: [ function (data) { let ret = '' for (let it in data) { ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&' } ret = ret.substring(0, ret.lastIndexOf('&')); return ret } ], headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).then(res => { this.rst = res.data }) ``` # 现象 PostMan请求接口返回的数据 ![postman](https://www.zunmx.top/usr/uploads/2021/08/3274249916.png) 不加transformRequest时 ![old](https://www.zunmx.top/usr/uploads/2021/08/792108123.png) 加transformRequest时 ![new](https://www.zunmx.top/usr/uploads/2021/08/396457688.png) # 前端Demo ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Demo</title> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <div id="app"> <span>id</span><input v-model="id" style="width:120px;"/> <br/> <span>name</span><input v-model="name" style="width:120px;"><br/> <span>sex</span><input v-model="sex" style="width:120px;"> <button @click="req" style="width:120px;">request</button> <br/> <span>resu </span><input type="text" readonly v-model="rst" style="width:300px;"> </div> </body> <script> var app = new Vue({ el: "#app", data: { id: 0, name: "", sex: "", rst: "" }, methods: { req: function () { axios({ method: 'post', url: 'http://127.0.0.1:8080/test', data: {"id": this.id, "name": this.name, "sex": this.sex}, transformRequest: [ function (data) { let ret = '' for (let it in data) { ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&' } ret = ret.substring(0, ret.lastIndexOf('&')); return ret } ], headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).then(res => { this.rst = res.data }) } } }) </script> </html> ``` © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果觉得我的文章对你有用,请随意赞赏