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>
相关推荐
小明记账簿_微信小程序几秒前
js、node.js获取指定文件下的内容
前端
小明记账簿_微信小程序几秒前
h5中弹框出现后禁止页面滚动
前端
一个有故事的男同学8 分钟前
从零打造专业级前端 SDK (一):架构与工程化
前端·架构
小胖霞10 分钟前
node全栈系列(七)-增加验证码登录
前端·vue.js·node.js
董世昌4110 分钟前
箭头函数和普通函数有什么区别
开发语言·javascript·ecmascript
A242073493038 分钟前
js流程控制语句
开发语言·前端·javascript
yngsqq43 分钟前
二维异形排版、二维装箱(NPF碰撞检测)——CAD c#二次开发
开发语言·javascript·c#
AAA阿giao1 小时前
JavaScript 执行机制深度解析:从 V8 引擎到作用域链、变量提升与闭包的全面剖析
前端·javascript·面试
一水鉴天1 小时前
整体设计 定稿 之19 拼语言表述体系之2(codebuddy)
大数据·前端·人工智能·架构
低代码的未来1 小时前
React CVE-2025-55182漏洞排查与修复指南
前端