【问题标题】:Proxying to different dynamic domains in a VueJS app代理到 VueJS 应用程序中的不同动态域
【发布时间】:2021-09-10 16:11:33
【问题描述】:

在我们的 VueJS 应用程序中,我有一个从指向 amer.example.com/put/stuff 的 API 返回的 URL,我需要输入一些数据。

显然,当我执行此 PUT 操作时,我得到了 CORS 错误。为了解决这个问题,我有一个devServer 代理设置,它说要重新路由所有/put/stuff 以通过example.com,如下所示:

devServer: {
  port: 9034,
  proxy: {
    '/put/stuff': {
      target: 'amer.example.com',
    },
  },
},

瞧,事情又开始了。

但是,从 API 返回的 URL 是动态的,可以指向另一个区域,例如 EMEA,emea.example.com/put/stuff,但 URL 中的其他所有内容都完全相同。

如何使代理动态化,以便它可以根据我从另一个 API 返回的 URL 转到 amer.example.comemea.example.com 或任何其他区域。

没有控制其他 API 以及返回的 URL 的形状。

【问题讨论】:

    标签: javascript vue.js http-proxy


    【解决方案1】:

    我能想到的唯一方法是丑陋的,但它应该可以工作。

    TLDR

    将区域插入到您从 API 返回的 URL 的路径中,然后在代理中查找该路径。最后在您的代理中使用 pathRewrite 将其从 URL 中删除。

    更长的解释

    在您的 methods 中创建一个新函数,将区域插入 URL 路径,如下所示:

    methods: {
      insertRegionIntoUrlPath(urlStr) {
        const url = new URL(urlStr);
    
        // Grab the region from the url, if it includes 'https://' then update the substring obviously).
        const regionPath = `/${url.hostname.substring(0,4)}`;
    
        // Set the path to now include the region in the beginning
        url.pathname = `${regionPath}${url.pathname}`;
    
        // Return the full URL that now contains the region: `https://amer.example.com/amer/put/stuff`
        return url.href;    
      },
    }
    

    然后,您可以在 PUT 发生的任何地方使用此函数将该区域添加到 URL 路径中。

    我假设您的区域总是4 个字符长,如果可能不同,那么只需使用一些正则表达式来提取子域。

    然后在您的代理设置中,您现在可以定位您想要的特定区域路径并删除您添加的部分路径,如下所示:

    module.exports = {
      devServer: {
        proxy: {
          '/amer': {
            target: 'https://amer.example.com',
            pathRewrite: {'^/amer' : ''} // Removing `/amer` from the path
          },
          '/emea': {
            target: 'https://emea.example.com/',
            pathRewrite: {'^/emea' : ''} // Removing `/emea` from the path
          }
        }
      }
    };
    

    所以现在您所做的是从 API 获取一个 URL,将区域添加到路径中并发出 PUT 请求,最后代理接收这些请求,因为它们将匹配区域路径,例如 /amer,然后我们只需在发送请求之前让代理从 URL 中删除该部分即可。

    【讨论】:

      猜你喜欢
      • 2012-06-16
      • 2016-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-12
      • 2019-08-14
      • 2020-04-04
      • 1970-01-01
      相关资源
      最近更新 更多