vue-cli 2.x连多个后台&前端使用proxyTable解决跨域问题

零、axios模块引入

npm install axios

然后在你需要的地方开头写 import axios from 'axios'即可,我这里是在axios/index.js里面使用了,全部代码看下面。

一、axios二次封装

要想连两个后台,原理就是在vue-cli配置文件中封装axios的地方创建两个axios实例,然后在你写的接口api位置调用具体的某个axios即可。所以我们首先先封装axios,我这里是封装在了axios/index.js里面的,全部代码如下:

import axios from 'axios'
import store from '@/store'
import router from '../router'
import sessionStorage from '@/utils/sessionStorage'
function request(config){
    //1.创建axios实例
    const instance1 = axios.create({
        baseURL:"http://11.1.1.11:8086/la", //我随便编的url地址
        timeout: 5000
    })

    const instance2 = axios.create({
        baseURL:"http://22.2.2.22:8080/zhou",//我随便编的url地址
        timeout: 50000
    })
    //request拦截器
    instance1.interceptors.request.use(
        config => {
            //每次发送请求之前检测都vuex存有token,那么都要放在请求头发送给服务器
            if(store.getters.token){
                config.headers.Authorization = store.getters.token;
            }
            return config;
        },
        err => {
            return Promise.reject(err);
        }
    );
    //respone拦截器
    instance1.interceptors.response.use(
        response => {
            if(response){
                if(response.data.data == 10001){
                    store.dispatch('UserLogout')
                    router.replace({
                        path:'/login',
                        query:{
                            redirect: router.currentRoute.fullPath
                        }
                    })
                }
                
            }
            return response;
        },
        error => { //默认除了2XX之外的都是错误的,就会走这里
            if(error.response){
                switch(error.response.status){
                    case 401:
                        store.dispatch('UserLogout'); //可能是token过期,清除它
                        router.replace({ //跳转到登录页面
                            path: 'login',
                            query: { redirect: router.currentRoute.fullPath } // 将跳转的路由path作为参数,登录成功后跳转到该路由
                        });
                }
            }
            return Promise.reject(error.response);
        }
    );
    //发送真正的网络请求
    return [instance1,instance2]
}
export default request()


   

如果你不对实例进行拦截器处理,简化以后就是这样的:

import axios from 'axios'
import store from '@/store'
import router from '../router'
import sessionStorage from '@/utils/sessionStorage'
function request(config){
    //1.创建axios实例
    const instance1 = axios.create({
        baseURL:"http://11.1.1.11:8086/la", //我随便编的url地址
        timeout: 5000
    })

    const instance2 = axios.create({
        baseURL:"http://22.2.2.22:8080/zhou",//我随便编的url地址
        timeout: 50000
    })
    //发送真正的网络请求
    return [instance1,instance2]
}
export default request()


   

二、接收实例

两个实例都暴露出来了,你只需要在你代码封装接口的api里(我这里是在api/area.js里面)指定具体的实例即可。代码如下

import request  from '../axios'; //首先得引入axios/index.js里面的实例request
export default{
    queryIcAreaInfoList(data){
        return request[1]({ //这里使用的是axios/index.js里面的第二个baseURL
            url:'/area/queryIcAreaInfoList',
            method:'post',
            data:data
        })
    },
    bookroom(data){
        return request[0]({ //这里使用的是axios/index.js里面的第一个baseURL
            url:'/bookroom/insert',
            method:'post',
            data:data
        })
    },
}

然后在你.vue代码里面调用你需要的接口就可以了

至此就完成了一个前端调用多个后台的操作啦,是不是很简单~

 

下面我们解决一下跨域问题。

就拿上面的例子举例,如果我们实例化的instance2存在跨域问题,那么我们需要使用proxyTable来解决。需要改的地方如下:

首先,在axios/index.js里面把instance2的baseURL改为随便一个单词,我这里为“/api":

import axios from 'axios'
import store from '@/store'
import router from '../router'
import sessionStorage from '@/utils/sessionStorage'
function request(config){
    //1.创建axios实例
    const instance1 = axios.create({
        baseURL:"http://11.1.1.11:8086/la", //我随便编的url地址
        timeout: 5000
    })

    const instance2 = axios.create({
        baseURL:"/api",//用/api来替代我们要访问的url地址
        timeout: 50000
    })
    //发送真正的网络请求
    return [instance1,instance2]
}
export default request()

然后,在config/index.js文件里面配置proxyTable,完整代码如下:

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.

const path = require('path')

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target:'http://22.2.2.22:8080/zhou', //这里就是刚刚用api替换的url地址
        changeOrigin: true,
        withCredentials:true,
        pathRewrite: {
          '^/api': ''
        }
      }
    },

    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: false,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-

    
    /**
     * Source Maps
     */

    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',

    // If you have problems debugging vue-files in devtools,
    // set this to false - it *may* help
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true,

    cssSourceMap: true
  },

  build: {
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist/'),
    assetsSubDirectory: 'static',
    assetsPublicPath: './',

    /**
     * Source Maps
     */

    productionSourceMap: true,
    // https://webpack.js.org/configuration/devtool/#production
    devtool: '#source-map',

    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],

    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  }
}

你的配置可以和我的有些区别,但是需要更改的其实只是这一段(注意target的url一定要以http://开头的哦):

    proxyTable: {
      '/api': {
        target:'http://22.2.2.22:8080/zhou', //这里就是刚刚用api替换的url地址
        changeOrigin: true,
        withCredentials:true,
        pathRewrite: {
          '^/api': ''
        }
      }

然后调用啥的都不用改,只需要改着两个位置就可解决跨域问题,如果多个后台url都有跨域问题,那么就在proxyTable多加几个,做成列表就可以啦。

你可能感兴趣的:(web前端)