Vue configuration proxy combat (development environment)

1. Configure proxy - vue.config.js


const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  // 配置代理服务器
  devServer: {
    proxy: {
      '/baidu': {
        target: 'https://baidu.com',
        // ws: true,                            // 用于支持websocket
        changeOrigin: true,                  // 用于控制请求头中的host值
        pathRewrite: {
          '^/baidu': ''
        }
      },
      // 配置更多代理...
    }
  }
})

As can be seen from the figure above, configure a  /baidu proxy, when /baidu is matched  , it will jump to the target target   https://baidu.com

2. Encapsulate axios.js 

Directory: utils/axios.js

Because the baseUrl configuration of axios will affect the proxy configured in vue.config.js, which may invalidate it. Therefore, baseURL needs to be processed according to url. If it is a proxy path, baseURL is set to empty

import axios from 'axios'  // 导入axios


/**
 * 当前路径是否为需要代理的路径
 * @param {*} url 
 * @returns 
 */
function currentUrlIsProxy(url) {
    const proxyArr = ['baidu','代理路径2','代理路径3'] // 需要代理的路径数组 - 即vue.config.js 中配置的代理路径集合
    const activeProxy = proxyArr.find(proxyItem => url.indexOf(proxyItem) !== -1)
    return activeProxy ? true : false
}

/**
 * axios请求
 * @param {*} method 
 * @param {*} url 
 * @param {*} params 
 * @param {*} headers 
 * @returns 
 */
export function apiAxios (method, url, params, headers) {
    var httpDefault = {
      baseURL: currentUrlIsProxy(url) ? '' : process.env.VUE_APP_BASE_URL,//基本地址
      method: method,//请求的方法
      url: url,//接口地址
      params: method === 'GET' || method === 'DELETE' ? params : null,//get请求和delete请求参数在url地址后面,不在请求体当中
      data: method === 'POST' || method === 'PUT' ? params : null,//put请求,post请求参数在请求体当中
      headers:headers?Object.assign({}, axios.defaults.headers,headers):axios.default.headers,//判断接口有没有定制的请求头,与基本的请求头进行合并
    }
    return new Promise((resolve, reject) => {
      axios(httpDefault)
        .then((res) => {
          resolve(res)
        }).catch((response) => {
          reject(response)
          // this.$message.error('请求失败!')
        })
    })
}

3. main.js enables the packaged axios.js to be used globally

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import { apiAxios } from './utils/axios' // 导入

Vue.config.productionTip = false
Vue.prototype.$http = apiAxios // 全局配置

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

Four. Use

Use component's .vue

<template>
  <div>

  </div>
</template>

<script>
export default {
    data() {
        return {

        }
    },
    mounted() {
        this.$http('get','/login_register_index',{request_time: '1663311028554'}).then(() => {
            // 这里的baseUrl 为 https://market.idcsmart.com
            // 这里实际请求的是  https://market.idcsmart.com/login_register_index
        }).catch(error => {
            console.log(error)
        })

        this.$http('get','/baidu/login_register_index',{request_time: '1663311028554'}).then(() => {
            // 匹配到 代理路径 /baidu
            // 这里实际请求的是  https://www.baidu.com/login_register_index  说明代理配置成功!
        }).catch(error => {
            console.log(error)
        })

    }
}
</script>

<style>

</style>

Guess you like

Origin blog.csdn.net/qq_39549013/article/details/126892513