vue之proxyTable代理全面配置的方法

发布时间:2022-04-14 13:49:34 作者:iii
来源:亿速云 阅读:256

本篇内容介绍了“vue之proxyTable代理全面配置的方法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

介绍

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

配置分离

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

vue之proxyTable代理全面配置的方法

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

vue之proxyTable代理全面配置的方法

以/default开头的api

vue之proxyTable代理全面配置的方法

“vue之proxyTable代理全面配置的方法”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

推荐阅读:
  1. vue中的代理转换机制proxyTable配置项
  2. vue如何配置跨域代理

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue proxytable

上一篇:基于jquery怎么实现简单轮播图效果

下一篇:Java线程安全与同步实例分析

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》