• 9. axios发送请求
  •  9.0. axios的引入:
  •  9.1. axios的基本使用:
  •   9.1.1. axios发送get请求
  •   9.1.2. axios发送post请求:
  •  9.2. axios使用别名发送请求:
  •   9.2.1. axios.get()发送get请求
  •   9.2.2. axios.post()发送post请求
  •  9.3. axios使用小总结:
  •  9.4. axios的全局配置:
  •  9.5. axios的实例配置:
  •  9.6. axios的拦截器:
  •  9.7. axios的封装使用:


9. axios发送请求

Axios 是基于 promise 对Ajax的封装

和Vue一样,对于初学者,推荐使用cdn形式引入:

<head>
    <meta charset="UTF-8">
    <title>axios</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>

 发送请求时,url 是必选的配置,此外可选配置有baseURL、methods、data、params、timeout等等
 具体可以查看官网:axios官网介绍

@RequestMapping(value = "axios")
    public String axios() {
        return "axios";
    }

    @RequestMapping(value = "/test/axiosGet")
    @ResponseBody
    public String axiosGet(HttpServletRequest request) {
        String name = request.getParameter("name");
        System.out.println("-------------------name: " + name);
        return "axiosGet";
    }
<div id="test-axios">
    <button @click="axiosGetOne">axiosGetOne</button>
</div>

<script>
    new Vue({
        el: '#test-axios',
        methods: {
            axiosGetOne: function () {
                axios({
                    url: '/axiosGet',
                    baseURL: '../test',			//`baseURL` 会被加到`url`前面,除非`url`已经写全了。
                    method: 'get',				//默认也是get请求
                    params: {
                        id: 1,
                        name: 'zhangsan'
                    }
                }).then(function (response) {   // 请求成功处理
                    console.log(response.data); //data即后端返回的数据"axiosGet"
                }).catch(function (error) {     // 请求失败处理
                    console.log(error);
                });
            }
        }
    });
</script>

 后端控制器打印zhangsan;页面控制器输出axiosGet

 发送有参get请求,使用params来发送参数;当然对于get请求,参数也可以携带在url上/test/axiosGet?id=1&name=zhangsan

  【使用data传递参数】:

 参数在data中携带,请求虽然能成功,但是后端获取不到请求数据
·
 那是因为axios发送post请求时,默认发送的是json格式的数据,后端request.getParameter和@RequestParam是获取不到的

@RequestMapping(value = "/test/axiosPost", method = RequestMethod.POST)
    @ResponseBody
    public String axiosPost(HttpServletRequest request) {
        String id = request.getParameter("id");
        System.out.println("-------------------id: " + id);
        return "axiosPost";
    }
<div id="test-axios">
    <button @click="axiosGetOne">axiosGetOne</button>
    <button @click="axiosPost">axiosPost</button>
</div>

<script>
    new Vue({
        el: '#test-axios',
        methods: {
            axiosPost: function () {
                axios({
                    url: '/axiosPost',
                    baseURL: '../test',
                    method: 'post',
                    data: {
                        id: 1,
                        name: 'zhangsan'
                    }
                }).then(response => {           // 请求成功处理
                    console.log(response.data); //data即后端返回的数据"axiosPost"
                }).catch(error => {             // 请求失败处理
                    console.log(error);
                });
            }
        }
    });
</script>

 请求发送的是json格式的数据,后端request.getParameter无法获取参数,当然,后端用@RequestBody注解的(实体类或Map)还是可以接收到的
 当然,我们不可能每个请求都去封装个实体类,那怎么办呢?往下看⬇

@RequestMapping(value = "/test/axiosPostBean", method = RequestMethod.POST)
    @ResponseBody
    public String axiosPostBean(@RequestBody User user) {
        System.out.println("-------------------id: " + user.getId());
        return "axiosPost";
    }

  【使用params传递参数】:

 上述问题,当我们使用params来传递参数,post请求成功,并且后端能够获取数据
·
 那是因为使用params,将请求参数都已键值对的形式拼接到url上了,但它还是POST请求

axios vue 请求原理 vue axios发送请求_ajax


  【使用URLSearchParams封装来传递参数】:

 使用URLSearchParams,参数不会拼接到url,后端可以request.getParameter获取参数

<script>
    var params = new URLSearchParams();
    params.append('id', 1);
    params.append('name', 'zhangsan');
    new Vue({
        el: '#test-axiosPost',
        methods: {
            axiosPostOne: function () {
                axios({
                    url: '/axiosPost',
                    baseURL: '../test',
                    method: 'post',
                    data: params
                }).then(response => {           // 请求成功处理
                    console.log(response.data); //data即后端返回的数据"axiosGet"
                }).catch(error => {             // 请求失败处理
                    console.log(error);
                });
            },
        }
    });
</script>


 axios支持使用别名发送所有类型的请求,如axios.get()、axios.post、axios.put()等等

 axios.get(url,{config}),和axios基本用法中差不多。

<div id="test-axiosInstance">
    <button @click="axiosGetOne">axiosGetOne</button>
</div>

<script>
    new Vue({
        el: '#test-axiosInstance',
        methods: {
            axiosGetOne: function () {
                axios.get('../test/axiosGet', {
                    params: {
                        id: 1,
                        name: 'zhangsan'
                    }
                    timeout: 5000
                }).then(response => {               // 请求成功处理
                    console.log(response.data);     //data即后端返回的数据"axiosGet"
                }).catch(error => {                 // 请求失败处理
                    console.log(error);
                });
            },
        }
    });
</script>

 axios.post(url,{data},{config}),和axios基本用法中差不多。但是参数要使用"id=1&name=‘zhangsan’"键值对的形式传递

 这种形式,参数不会拼接在url

<div id="test-axiosInstance">
    <button @click="axiosPost">axiosPost</button>
    <button @click="axiosPostBean">axiosPostBean</button>
</div>

<script>
    new Vue({
        el: '#test-axiosInstance',
        methods: {
            axiosPost: function () {
                axios.post('../test/axiosPost', "id=1&name='zhangsan'")
                    .then(response => {                 // 请求成功处理
                        console.log(response.data);     //data即后端返回的数据"axiosPost"
                    })
            },

            axiosPostBean: function () {
                axios.post('../test/axiosPostBean', {
                        id: 1,
                        name: 'zhangsan'
                    }, {
                        timeout: 5000				 //请求超时时间
                    }
                ).then(response => {                 // 请求成功处理
                    console.log(response.data);     //data即后端返回的数据"axiosPost"
                })
            }
        }
    });
</script>
@RequestMapping(value = "/test/axiosPostBean", method = RequestMethod.POST)
    @ResponseBody
    public String axiosPostBean(@RequestBody User user) {
        System.out.println("-------------------id: " + user.getId());
        return "axiosPost";
    }

 参数不使用键值对的形式,仍然使用data形式,同axios基本用法中一样,后端要用@RequestBody注解的(实体类或Map)接收才能获取参数

// 请求参数为键值对,后端可以使用request.getParamter或@requestParam获取参数
// 请求为json数据,后端使用@RequestBody注解的(实体类或Map)获取参数
// get请求发送的时键值对参数,post请求发送的是json格式参数

// axios基本格式使用中,post请求参数使用params来发送,参数会拼接到url;或者使用URLSearchParams来封装参数传递,后端都能使用request.getParamter获取参数
// axios.post发送post请求,参数采用params来发送,参数不会拼接url,后端都能使用request.getParamter获取参数

 全局配置就是所有的axios都使用配置,一般将请求的一些共有设置进行全局配置,如timeout、baseURL等

axios.default.baseURL = "../test"
    axios.default.timeout = 5000;
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    axios.get(...,...);

 当然,对于配置的优先级,请求中的配置>axios实例的配置>全局配置

 axios.get()等使用的时默认的实例,当然我们可以通过axios.create来创建符合场景实例,在实例中可以对实例配置

<script>
    // 创建实例时设置默认配置
    const instance = axios.create({
        baseURL: '../test',
        timeout: 3000
    });
    // 实例创建后还可以更改配置
    instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    // 实例发送请求
    instance.get(..,..)
</script>

 可以拦截请求或者响应在他们被 then 或 catch 处理之前。

 请求拦截器:请求之前进行拦截;axios.interceptors.request.use(成功函数,失败函数)

<script>
    axios.interceptors.request.use(config => {
        console.log(config)
        console.log(config.params)
        return config;
    }, err => {
        console.log(err)
    });
</script>

 响应拦截器:请求成功响应之前进行拦截;axios.interceptors.response.use(成功函数,失败函数)

<script>
    axios.interceptors.response.use(config => {
        console.log("----: " + config.data)
        return config.data;
    }, err => {
        console.log("====:" + err
        )
    });
</script>

 一个项目都会有很多请求,如果每个请求都写这么长的axios,这相当不美观,所以一般都会封装axios来使用