vue3+vite+axios 配置连接后端调用接口的实现方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue3+vite+axios 配置连接后端调用接口的实现方法

专心致志的程序员!   2022-12-08 我要评论

vite.config.ts文件中添加以下配置

export default defineConfig({
  plugins: [vue()],
  optimizeDeps: {
    include: ['axios'],
  },
  build: {
    target: 'modules',
    outDir: 'dist',
    assetsDir: 'assets',
    minify: 'terser' // 混淆器
  },
  server: {
    cors: true,
    open: true,
    proxy: {
      '/api': {
        target: 'http://xxx.xxx.xxx',   //代理接口
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  }
})

在本地项目中新建一个文件夹api文件夹中编写以下文件

1.配置axiosaxios.js

import axios from "axios"

const instance = axios.create({
  baseURL: "/api",
  timeout: 5000,
});

// 添加请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么
    config.headers["Content-type"] = "application/json";
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    // 隐藏加载图
    // 获取code
    const res = response.data;
    // 返回成功
    if (res == 200) {
      return res;
    }
    // token 异常
    if (res === 508 || res === 512 || res === 514) {
      // 登出 清除token缓存
    }
    return response;
  },
  (error) => {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

export default instance;

2.配置请求(request.js

import instance from "./axios"
const axios = ({
    method,
    url,
    data,
    config
}) => {
    method = method.toLowerCase();
    if (method == 'post') {
        return instance.post(url, data, {...config})
    } else if (method == 'get') {
        return instance.get(url, {
            params: data,
            ...config
        })
    } else if (method == 'delete') {
        return instance.delete(url, {
            params: data,
            ...config
        }, )
    } else if (method == 'put') {
        return instance.put(url, data,{...config})
    } else {
        console.error('未知的method' + method)
        return false
    }
}
export default axios

3.配置端口
编写具体的请求,建议按照项目具体情况分文件编写

import axios from "./request"
//请求示例
//get
export const mokeGet = (data) => {
    return axios({
        url: "/getTest",
        method: "get",
        data,
        config: {
            headers: {
                'Request-Type': 'wechat'
            },
            timeout: 3000
        }
    })
}
post
export const mokePost = (data) => {
    return axios({
        url: "/postTest",
        method: "post",
        data,
        config: {
            headers: {
                'Request-Type': 'wechat'
            },
            timeout: 3000
        }
    })
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们