vue之proxyTable代理超全面配置流程

目录
  • 前言
  • 介绍
  • 配置分离
    • 1. config.dev.js
    • 2. proxyTableHandler.js
  • 效果如下

    前言

    用了vue有一年多了,从最初的摸着石头过河到现在已经能熟练的使用vue开发项目,学到了许多,特别是vue的代理配置让我眼前一亮,甚是喜欢,故将自己对proxyTable代理配置整理出来,供致力于的开源的同辈浏览,望大家手下留情,哈哈_。

    介绍

    vue的proxyTable是用于开发阶段配置跨域的工具,可以同时配置多个后台服务器跨越请求接口,其真正依赖的npm包是http-proxy-middleware,在github上拥有更丰富的配置,按需配置咯。

    配置分离

    我将代理配置抽离出2个配置文件

    1. config.dev.js

    用于配置后端服务器地址、端口和IP等

    2. proxyTableHandler.js

    用于添加代理的配置项

    config.dev.js如下

    /*
    * 开发环境服务器配置
    * @Author: wujiang
    * @Date: 2018-08-16 11:32:36
    * @Last Modified by: wujiang
    * @Last Modified time: 2018-08-18 23:04:34
    */
    module.exports = {
       // 开发环境代理服务器
       devProxy: {
           host: '0.0.0.0', // ip/localhost都可以访问
           port: 8080
       },
       // 后端服务器地址
       servers: {
         default: 'http://localhost:8081/springboot-girl',
         jsp: 'http://localhost:8082/springboot-jsp'
       }
    }
    

    proxyTableHandler.js如下

    /*
     * 开发环境代理配置 生产环境请使用 nginx 配置代理 或 其他方式
     * @Author: wujiang
     * @Date: 2018-08-16 17:16:55
     * @Last Modified by: wujiang
     * @Last Modified time: 2018-08-19 09:18:18
     */
    const configDev = require('../config.dev')
    module.exports = (() => {
    	let proxyApi = {}
        let servers = configDev.servers
        for (let key of Object.keys(servers)) {
            proxyApi[`/${key}`] = {
                // 传递给http(s)请求的对象
                target: servers[key],
                // 是否将主机头的源更改为目标URL
                changeOrigin: true,
                // 是否代理websocket
                ws: true,
                // 是否验证SSL证书
                secure: false,
                // 重写set-cookie标头的域,删除域名
                cookieDomainRewrite: '',
                // 代理响应事件
                onProxyRes: onProxyRes,
                // 重写目标的url路径
                pathRewrite: {
                    [`^/${key}`]: ''
                }
            }
        }
        return proxyApi
    })()
    /**
     * 过滤cookie path,解决同域下不同path,cookie无法访问问题
     * (实际上不同域的cookie也共享了)
     * @param proxyRes
     * @param req
     * @param res
     */
    function onProxyRes (proxyRes, req, res) {
      let cookies = proxyRes.headers['set-cookie']
      // 目标路径
      let originalUrl = req.originalUrl
      // 代理路径名
      let proxyName = originalUrl.split('/')[1] || ''
      // 开发服url
      let server = configDev.servers[proxyName]
      // 后台工程名
      let projectName = server.substring(server.lastIndexOf('/') + 1)
      // 修改cookie Path
      if (cookies) {
          let newCookie = cookies.map(function (cookie) {
              if (cookie.indexOf(`Path=/${projectName}`) >= 0) {
                  cookie = cookie.replace(`Path=/${projectName}`, 'Path=/')
                  return cookie.replace(`Path=//`, 'Path=/')
              }
              return cookie
          })
          // 修改cookie path
          delete proxyRes.headers['set-cookie']
          proxyRes.headers['set-cookie'] = newCookie
      }
    }
    

    使用方式 config/index.js

    const configDev = require('./config.dev')
    module.exports = {
    	dev: {
        // Paths
        assetsSubDirectory: 'static',
        assetsPublicPath: '/',
        proxyTable: proxyTableHandler,
        // Various Dev Server settings
        host: configDev.devProxy.host, // can be overwritten by process.env.HOST
        port: configDev.devProxy.port, // 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-
        // Use Eslint Loader?
        // If true, your code will be linted during bundling and
        // linting errors and warnings will be shown in the console.
        useEslint: true,
        // If true, eslint errors and warnings will also be shown in the error overlay
        // in the browser.
        showEslintErrorsInOverlay: false,
        /**
         * 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
      }
    }
    

    效果如下

    以/jsp开头的api

    以/default开头的api

    至此配置代理成功!

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持。 

    本文转自网络,如有侵权请联系客服删除。