Vue-cli 请求代理配置,封装 Axios

Vue-cli 请求代理配置及封装 Axios

博主wx: -GuanEr-,加博主进前端交流群

一、HTTP 请求代理配置

1.1 vue-cli 2.x

// /config/index.js
proxyTable: {
  '/api-1': {
    target: 'http://xxx.xxx.xxx.xxx:8080',
    changeOrigin: true,
    pathRewrite: {
      // 以 /api-1 开头的请求路径都会被 'http://xxx.xxx.xxx.xxx:8080' 代理
      '^/api-1': '' 
    }
  },
  '/api-2': {
    target: 'http://xxx.xxx.xxx.xxx:8081',
    changeOrigin: true,
    pathRewrite: {
      // 以 /api-2 开头的请求路径都会被 'http://xxx.xxx.xxx.xxx:8081' 代理
      '^/api-2': ''
    }
  }
}

1.2 vue-cli 3.x

// vue.config.js(该文件在项目的根目录下,默认没有这个文件,用时需要自己新建)
module.exports = {
  devServer: {
    proxy: {
      '/api-1': {
        target: 'http://xxx.xxx.xxx.xxx:8080',
        ws: true, // 是否开启 websokets
        secure: false, // 是否安全,https 为 true,http 为 false
        changeOrigin: true,
        pathRewrite: {
          '^/api-1': ''
        }
      },
      '/api-2': {
        target: 'http://xxx.xxx.xxx.xxx:8081',
        ws: true,
        secure: false,
        changeOrigin: true,
        pathRewrite: {
          '^/api-2': ''
        }
      }
    }
  }
};

1.3 调用

axios({
  // xxxx/xxxx 为代理配置的 target 后的路径 
  url: '/api-1/xxxx/xxxx',
  ...
});

二、Axios 封装

2.1 封装请求共用函数

变换较大的、常用的参数放前面,不常改变的参数和有默认值的参数放在参数队列最后。

// /src/api/ajax.js (该目录及名称可自定义)
import axios from 'axios'
const request = axios.create({
  // 生产环境和开发环境的请求域名和端口
  baseURL: process.env.NODE_ENV === 'production' ? 'http://192.168.0.247:92/' : '',
  withCredentials: false
});
request.interceptors.request.use(config => {
  // 请求拦截器,可在此做请求之前的处理,比如绑定 token,存储或清除某些数据等
  return config;
});
request.interceptors.response.use(res => {
  // 响应拦截器,可在此处做统一的请求失败处理等操作
  console.log(res);
});
export default function ajax(
  url,
  params = {},
  type = 'post',
  errorCallBack,
  header = {headers: {'Content-Type': 'application/json'}}
) {
  return new Promise(resolve => {
    request[type](url, type === 'get' ? {params} : params, header)
      .then(res => resolve(res.data))
      .catch(e => {
        errorCallBack && errorCallBack();
        console.log(e);
      });
  });
}

2.2 封装项目中的请求列表列表

// /src/api/index.js (该目录及名称可自定义)
import ajax from "./ajax";
const API1 = '/api-1';
const API2 = '/api-2';

// params 是个对象,存放请求所有参数列表
const req1 = params => ajax(API1 + '/xxx/xxx/xxx', params);
const req2 = params => ajax(API2 + '/xxx/xxx/xxx', params);

export default {
  req1,
  req2
}

2.3 在 main.js 配置

2.3.1 原始配置方式,将请求绑定给 Vue 原型,方便各个组件继承使用
// main.js
...
import $http from './api'
Vue.prototype.$http = $http;
...
2.3.2 createApp 函数配置方式
...
import $http from './api'

// 这里要注意代码的先后顺序不能变
const app = createApp(App);
app.config.globalProperties.$http = $http;
app.use(store).use(router).mount('#app');
...

2.4 在任意组件中的调用

export default {
  name: 'xxx',
  methods: {
    async req() {
      // res为请求返回值,如果要传其他值,看上面封装的 ajax 函数的参数列表 
      const res = await this.$http.req1({
        ... // 参数列表
      });
    }
  }
}

扫码拉你进入前端技术交流群

在这里插入图片描述

  • 8
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

锋利的二丫

如果对您有帮助,请博主喝杯奶茶

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值