Skip to content

Vue 使用 axios 访问 api

Vue 使用 axios 访问 api

简介

Axios 是一个基于 Promise 的用于浏览器和 Node.js 的 HTTP 客户端。它可以使在浏览器和 Node.js 中发送 HTTP 请求变得更加容易,它支持许多功能,比如自动转换 JSON 数据、发布异步请求、拦截请求和响应、设置请求头等。

官网地址

axios 的特性

axios 具有以下特点:

  • Promise封装:axios 使用 Promise 封装了 HTTP 请求,使得异步处理更为便捷。
  • 浏览器和 Node.js 兼容:axios 可以同时在浏览器和 Node.js 环境中使用,使得它非常灵活。
  • 拦截器:可以在请求或响应被处理前拦截它们,允许对请求或响应进行全局的处理。
  • 取消请求:可以取消未完成的请求,防止出现不必要的网络请求。
  • 请求和响应拦截:可以在请求被发送或响应被接收时执行特定的操作,如在请求中添加特定的头信息,或者在响应中处理特定的数据。
  • 防止CSRF攻击:可以通过设置 headers 或者使用 Cookie 来防止 CSRF 攻击。

axios 安装

在项目中使用 axios 时,首先需要在项目中使用 npm 进行安装 axios。

npm install axios

axios 发送GET请求

Axios 对所支持的所有请求都提供了别名,方便开发者更直观的使用。

axios.get(url[, config]) 用来发送 GET 方式的请求。

<template>
    <div>
        <button @click="sendGetRequest">发送GET请求</button>
        <button @click="sendGetRequestWithParams">发送GET请求(使用params)</button>
    </div>
</template>

<script setup>
    import axios from 'axios';

    // 发起GET请求,通过URL传递参数
    const sendGetRequest = () => {
        axios.get('https://httpbin.ceshiren.com/get?id=123')
        .then((response) => {
            alert('GET请求成功');
            console.log(response)
        })
        .catch((error) => {
            console.error('GET请求错误:', error);
        });
    }

    // 发起GET请求,通过params传递参数
    const sendGetRequestWithParams = () => {
        axios.get('https://httpbin.ceshiren.com/get', {
            params: { id: 123 }
        })
        .then((response) => {
            alert('GET请求(使用params)成功');
            console.log(response)
        })
        .catch((error) => {
            console.error('GET请求错误:', error);
        });
    }
</script>

axios 发起 POST 请求

Axios 使用axios.post(url[, config]) 用来发送 POST 方式的请求。

JSON 格式请求体

Axios 在使用 POST 方式发起请求时,所任携带的数据,会使用 JSON 形式保存

<template>
    <div>
        <button @click="sendPostRequest">发送POST请求</button>
        <button @click="sendJsonRequest">发送 JSON 请求</button>
    </div>
</template>

<script setup>
    import axios from 'axios';

    // 发起POST请求
    const sendPostRequest = () => {
        axios.post('https://httpbin.ceshiren.com/post')
        .then((response) => {
            alert('POST请求成功');
            console.log(response)
        })
        .catch((error) => {
            console.error('POST请求错误:', error);
        });
    }

    // 发送 JSON 请求, POST 请求默认以 json 格式携带数据
    const sendJsonRequest = function () {
        const jsonData = { name: 'lily' }
        axios.post('https://httpbin.ceshiren.com/post', jsonData)
        .then((res) => {
            alert('JSON 请求成功');
            console.log(res)
        }).catch((err) => {
            console.log(err)
        })
    }

</script>

表单格式请求体

如果以表单格式携带请求数据,需要使用 FormData 对象,将数据以键值对形式追加到对象中,并设置请求头信息中的 'Content-Type' 值为 'multipart/form-data'

<template>
    <div>
        <button @click="sendFormRequest">发送 Form 表单请求</button>
    </div>
</template>
<script setup>
    import axios from 'axios';

    // 发送 Form 表单请求, post 如果以表单格式发送数据,需要 使用 FormData 对象
    const sendFormRequest = function () {
        // 
        const formData = new FormData();
        formData.append('name', 'lily');

        axios.post('https://httpbin.ceshiren.com/post', formData, {
            // 添加请求头,指定表单数据格式
            headers: {'Content-Type': 'multipart/form-data'}
        })
        .then((res) => {
            alert('Form 表单请求成功');
            console.log(res)
        }).catch((err) => {
            console.log(err)
        })
    }
</script>

小结

  • 发送 GET 请求时,可以将参数直接拼接在URL后,或放在配置对象的 params 属性中。
  • 发送 POST 请求时,数据默认形式为 JSON 格式。
  • 发送 POST 请求时,可以通过 FormData 对象,将请求数据追加进去,实现以表单格式数据请求。
  • 不同方式携带的请求数据,在服务端接口中对应使用不同的方法提取数据。