• vue3接口封装 亲测有效


    目录

    一. 安装axios     

    二. 配置axios,添加拦截器

    三、使用axios发送请求

    四.页面使用:


    一. 安装axios     

       npm install axios --save

    二. 配置axios,添加拦截器

    1.在src下新建文件夹request,在request内部新建index.js 文件

    2.内部放入以下代码:

    import axios from 'axios'

    // 创建一个 axios 实例

    const service = axios.create({

        baseURL: 'http://api.tubecoin.org', // 所有的请求地址前缀部分

        timeout: 60000, // 请求超时时间毫秒

        withCredentials: true, // 异步请求携带cookie

        headers: {

            // 设置后端需要的传参类型

            'Content-Type': 'application/json',

            'token': ' token',

            'X-Requested-With': 'XMLHttpRequest',

        },

    })

    // 添加请求拦截器

    service.interceptors.request.use(

        function(config) {

            // 在发送请求之前做些什么

            return config

        },

        function(error) {

            // 对请求错误做些什么

            console.log(error)

            return Promise.reject(error)

        }

    )

    // 添加响应拦截器

    service.interceptors.response.use(

        function(response) {

            console.log(response)

                // 2xx 范围内的状态码都会触发该函数。

                // 对响应数据做点什么

                // dataAxios 是 axios 返回数据中的 data

            const dataAxios = response.data

                // 这个状态码是和后端约定的 我这里没有用到 注释了

                // const code = dataAxios.reset

            return dataAxios

        },

        function(error) {

            // 超出 2xx 范围的状态码都会触发该函数。

            // 对响应错误做点什么

            console.log(error)

            return Promise.reject(error)

        }

    )

    export default service

    三、使用axios发送请求

    在src下新建api文件,内部放所有的请求文件,例如:新建request.js文件

    // 导入axios实例

    import httpRequest from '@/request/index'

    // 获取用户信息

    export function register(data) { //register是封装好的接口名

        return httpRequest({

            url: '/api/register/register',

            method: 'post',

            data,

        })

    }

    四.页面使用:


     

  • 相关阅读:
    网络基本概念
    数据结构——栈,队列,及其结构特点应用。
    【JVM】垃圾回收
    基础会计学原理重点整理(精编!!)
    编辑器库QsciScintilla的indicator点击没有按键信息的bug解决
    火狐浏览器如何关闭右侧的“百度热搜”
    Iocomp Components Full Sources Product
    Java面试题06
    案例!快看!电力行业利用IBPS低代码应用开发平台做好数据治理工作
    474. 一和零
  • 原文地址:https://blog.csdn.net/weixin_53935634/article/details/126518382