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>
相关推荐
Dxy123931021615 分钟前
JS发送请求的方法详解
开发语言·javascript·ecmascript
CHU72903519 分钟前
定制专属美丽时刻:美容预约商城小程序的贴心设计
前端·小程序
浩~~1 小时前
反射型XSS注入
前端·xss
AwesomeDevin1 小时前
AI时代,我们的任务不应沉溺于与 AI 聊天,🤔 从“对话式编程”迈向“数字软件工厂”
前端·后端·架构
harrain1 小时前
antvG2折线图和区间range标记同时绘制
前端·javascript·vue.js·antv·g2
德育处主任Pro1 小时前
从重复搭建到高效生产,RollCode的H5开发新范式
前端
蜡台2 小时前
SPA(Single Page Application) Web 应用(即单页应用)架构模式 更新
前端·架构·vue·react·spa·spa更新
网络点点滴2 小时前
组件通信-作用域插槽
前端·javascript·vue.js
LZQ <=小氣鬼=>3 小时前
React 图片放大镜组件使用文档
javascript·react.js·前端框架·ecmascript
kyriewen113 小时前
异步编程:从“回调地狱”到“async/await”的救赎之路
开发语言·前端·javascript·chrome·typescript·ecmascript·html5