axios的各种请求方法

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vue_3.2.36_vue.global.js"></script>
    <script src="js/axios_0.27.2_axios.js"></script>
</head>
<body>
<div id="app">
    <h1>网站列表</h1>
    <ul>
        <li v-for="site in sites">{{ site.name }}</li>
    </ul>
    <img id="image" :src="image" alt="">
</div>

<script>
    // 创建实例时设置默认的配置
    var instance = axios.create({
        baseURL: "https://www.baidu.com/api"
    })
    // 在实例创建后修改默认值
    instance.defaults.headers.common["Authorization"] = "123789"

    // 添加请求拦截器
    // 在发送请求之前做些什么
    instance.interceptors.request.use(function (config) {
        console.log("请求前执行了")
        return config
    })
    // 对响应数据做点什么
    instance.interceptors.response.use(function (resp) {
        console.log("对响应数据做了处理")
        return resp
    })

    const app = Vue.createApp({
        data() {
            return {
                sites: [],
                image: ""
            }
        },
        mounted() {
            // 直接url添加参数
            // axios.get("/info?idx=110")

            // 通过params添加参数
            /*
            axios.get("/info", {
                "params": {
                    "idx": 120
                }
            })
            */

            // post传参
            /*
            axios.post("/info", {
                "firstName": "My",
                "lastName": "YaNan"
            })
                .then((res) => {
                    this.sites = res.data.data.sites
                    console.log(res)
                })
                .catch(function (error) {
                    console.log(error)
                })
             */

            // 一次发送多个请求
            /*
            axios.all([this.getUserAccount(), this.getUserPermission()])
                .then(axios.spread(function (acct, perms) {
                    console.log(acct.data.data)
                    console.log(perms.data.data)
                }))
                .catch(function (error) {
                    console.log(error)
                })
            */

            // 可以通过向axios传递相关配置来创建请求
            // 001-请求图片
            /*
            axios({
                method: "post",
                url: "/img",
                responseType: "blob"
            })
                .then((response) => {
                    const imageBlob = new Blob([response.data], {type: response.headers['content-type']});
                    // 创建一个图片URL,用于显示图片
                    const imageUrl = URL.createObjectURL(imageBlob);
                    // 使用imageUrl来显示图片,例如将它设置为<img>元素的src属性
                    this.image = imageUrl
                })
                .catch(function (err) {
                    console.log(err)
                })
             */

            // 使用cancel token取消请求
            var CancelToken = axios.CancelToken;
            var source = CancelToken.source();

            // 及简get请求
            instance.get("info", {
                cancelToken: source.token
            })
                .then((res) => {
                    console.log(res)
                })
                // 错误处理
                .catch(function (error) {
                    if (axios.isCancel(error)) {
                        console.log("request cancled", error.message)
                    }else if (error.response){
                        console.log("状态码不是2xx")
                        console.log(error.response.data)
                        console.log(error.response.status)
                        console.log(error.response.headers)
                    }else {
                        console.log(error.message)
                    }
                })

            // 取消请求(message 参数是可选的)
            source.cancel('Operation canceled by the user.')

        },
        methods: {
            getUserAccount: function () {
                return axios.get("/userAccount")
            },
            getUserPermission: function () {
                return axios.get("/userPermission")
            }
        }
    })
    const vm = app.mount("#app")
</script>
</body>
</html>
相关推荐
知识分享小能手5 分钟前
Vue3 学习教程,从入门到精通,Axios 在 Vue 3 中的使用指南(37)
前端·javascript·vue.js·学习·typescript·vue·vue3
伍哥的传说30 分钟前
Mitt 事件发射器完全指南:200字节的轻量级解决方案
vue.js·react.js·vue3·mitt·组件通信·事件管理·事件发射器
程序员码歌3 小时前
【零代码AI编程实战】AI灯塔导航-总结篇
android·前端·后端
用户21411832636023 小时前
免费玩转 AI 编程!Claude Code Router + Qwen3-Code 实战教程
前端
一枚小小程序员哈3 小时前
基于Vue + Node能源采购系统的设计与实现/基于express的能源管理系统#node.js
vue.js·node.js·express
小小愿望5 小时前
前端无法获取响应头(如 Content-Disposition)的原因与解决方案
前端·后端
小小愿望5 小时前
项目启功需要添加SKIP_PREFLIGHT_CHECK=true该怎么办?
前端
烛阴5 小时前
精简之道:TypeScript 参数属性 (Parameter Properties) 详解
前端·javascript·typescript
海上彼尚6 小时前
使用 npm-run-all2 简化你的 npm 脚本工作流
前端·npm·node.js
开发者小天6 小时前
为什么 /deep/ 现在不推荐使用?
前端·javascript·node.js