当前位置:   article > 正文

Vue3全局配置跨域 axios并封装_vue3封装axios跨域

vue3封装axios跨域
Vue3全局配置跨域 axios并封装

1、引入axios

npm install axios
  • 1

2、基础配置

新建request.ts

import axios from "axios";

export function request(config) {

    const instance = axios.create({
        baseURL: 'http://127.0.0.1:8000/', // 通过/api别名指定后端路由
        timeout: 5000,
        headers: {},
    })
    // 添加请求拦截器
    instance.interceptors.request.use(function (config) {
        // 在发送请求之前做些什么
        return config;
    }, function (error) {
        // 对请求错误做些什么
        return Promise.reject(error);
    });

// 添加响应拦截器
    instance.interceptors.response.use(function (response) {
        // 2xx 范围内的状态码都会触发该函数。
        // 对响应数据做点什么
        return response;
    }, function (error) {
        // 超出 2xx 范围的状态码都会触发该函数。
        // 对响应错误做点什么
        if(error.response){
            if(error.response==500){
                alert('服务器发生错误')
            }
        }
        return Promise.reject(error);
    });

    //发送一个真正的请求
    return instance(config)
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

3、vite.config.ts中配置跨域

devServer: {
      proxy: {
          '/api': {
              target: 'http://127.0.0.1:8000/',// 后端接口
              changeOrigin: true, // 是否跨域
              pathRewrite: {
                  '/api': ''
              }
          }
      }
  },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

4、编写前端接口

export const getImage=()=>{
    return request({
        url:'/citydata/getImage',
        method:"get",
    })
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

5、在文件中引入

let image =getImage().then(res=>{
      imageurl=res.data
    })
    await image
  • 1
  • 2
  • 3
  • 4
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/447580
推荐阅读
相关标签
  

闽ICP备14008679号