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>
相关推荐
一斤代码4 分钟前
vue3 下载图片(标签内容可转图)
前端·javascript·vue
中微子7 分钟前
React Router 源码深度剖析解决面试中的深层次问题
前端·react.js
光影少年9 分钟前
从前端转go开发的学习路线
前端·学习·golang
中微子39 分钟前
React Router 面试指南:从基础到实战
前端·react.js·前端框架
3Katrina42 分钟前
深入理解 useLayoutEffect:解决 UI "闪烁"问题的利器
前端·javascript·面试
前端_学习之路2 小时前
React--Fiber 架构
前端·react.js·架构
coderlin_2 小时前
BI布局拖拽 (1) 深入react-gird-layout源码
android·javascript·react.js
伍哥的传说2 小时前
React 实现五子棋人机对战小游戏
前端·javascript·react.js·前端框架·node.js·ecmascript·js
qq_424409192 小时前
uniapp的app项目,某个页面长时间无操作,返回首页
前端·vue.js·uni-app
我在北京coding2 小时前
element el-table渲染二维对象数组
前端·javascript·vue.js