Vue开发中使用Axios组件发送请求到Springboot接口,后端无法接收到请求数据

今天开始使用axios结合springboot开发项目,碰到了Vue开发中使用Axios组件发送请求到Springboot接口,后端无法接收到请求数据的问题,查阅了很多资料遂解决做一个笔记。

具体操作:

前端:

    var dt = { id: this.id, name: this.name, ctime: new Date() }
    axios.post("/saveCar", dt).then(result => {
        if (result.data == "200") {
            this.getAllList()
        } else {
            console.log("error")
        }
    })

后端:

    @RequestMapping("/saveCar")
    public String saveCar(@RequestBody Car car, HttpServletResponse response){

        car.setCtime(car.getCtime().split("\\.")[0]);
        if (carDao.saveCar(car)){
            return "200";
        }else {
            return "500";
        }
    }

Why?

首先咱们来看ajaxaxios发送的请求区别

Vue开发中使用Axios组件发送请求到Springboot接口,后端无法接收到请求数据_第1张图片
ajax请求数据

Vue开发中使用Axios组件发送请求到Springboot接口,后端无法接收到请求数据_第2张图片
axios全球数据

那这里 ajax请求方式会把数据封装起来以data的方式发送到后台,而 axios请求方式则会把数据以params

那我们知道,data与params的区别就是前者是post请求,后者是get请求的传参方式,那就意味着我们之前指定的axios发送的请求默认又变成get请求了。

jquery在执行post请求时,会设置Content-Type为application/x-www-form-urlencoded,所以服务器能够正确解析,而使用原生ajax、axios请求时,如果不显示的设置Content-Type,那么默认是text/plain,这时服务器就不知道怎么解析数据了,所以才只能通过获取原始数据流的方式来进行解析请求数据。

解决方案

1、不改变axios请求方式,前文中的操作使用@RequestBody注释获取params的参数,并进行操作
2、改变axios请求方式,让axios能够正常的传输Form Data数据,具体实现方式就是在请求头中设置Content-Typeapplication/x-www-form-urlencoded

具体代码实现:

1、普通项目设置:

                var dt = { id: this.id, name: this.name, ctime: new Date() }
                axios({
                    url: "/saveCar",
                    method: 'post',
                    data: dt,
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded"
                    }
                }).then(result => {
                    if (result.data == "200") {
                        this.getAllList()
                    } else {
                        console.log("error")
                    }
                })

Vue项目设置:

import axios from 'axios';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Vue.prototype.$axios = axios;

参考:VUE axios 发送 Form Data 格式数据请求

你可能感兴趣的:(Vue开发中使用Axios组件发送请求到Springboot接口,后端无法接收到请求数据)