如何将自定义http标头添加到角度模块联合remoteEntry.js加载调用?

2024-04-28

我有一个主机应用程序和一些微前端应用程序都是 Angular 15。我用过"@angular-architects/module-federation": "^15.0.3"。一切工作正常,除了我无法拦截加载 mfe 应用程序的 remoteEntry.js 文件的 http 调用。

所有 mfe 应用程序都部署在服务器中,服务器要完成请求,我必须将授权令牌添加到请求中。我尝试了多种方法,但无法拦截该调用并将令牌添加到其中。

  1. Angular http 拦截器不会拦截此调用。
  2. 模块联合没有提供任何添加 http 请求的选项。

任何建议将不胜感激。

下面是我的路由,我在其中加载 mfe

{
        path: 'config',
        loadChildren: () =>
          loadRemoteModule({
            remoteEntry: environment.configREmoteEntryURL,
            type: "module",
            exposedModule: './Module'
          })
            .then(m => m.AppModule)
},

您可以使用 Service Worker 来拦截和操作所有针对 MFE CDN 的请求。

service-worker.js

let authToken = '';

// This event listeners listens to the requests towards the login
// endpoint and stores that authToken at the corresponding variable.
self.addEventListener('fetch', function (event) {
  if (event.request.url === 'https://auth-endpoint/login') {
    event.respondWith(
      fetch(event.request)
        .then(function (response) {
          var responseClone = response.clone();

          responseClone.json().then(function (data) {
            authToken = data.token;
          });

          return response;
        })
    );
  }
});

// This requests listens to the requests towards the MFEs' endpoint
// and adds the custom headers needed fot the authorization
self.addEventListener('fetch', function (event) {
  if (event.request.url.startsWith('https://remotes-endpoint/')) {
    let url = new URL(event.request.url);

    let headers = new Headers(event.request.headers);

    headers.set('Content-Type', 'application/javascript');
    headers.set('Authorization', authToken);

    let newRequest = new Request(url, {
      method: event.request.method,
      headers,
      mode: 'cors',
      credentials: 'same-origin',
      redirect: event.request.redirect
    });

    event.respondWith(fetch(newRequest));
  }
});

您需要在 bootstrap.js 中注册您的 Service Worker

...
if ('serviceWorker' in navigator) {
  window.addEventListener('load', function () {
    navigator.serviceWorker.register('/service-worker.js')
      .then(function (registration) {
        console.log('Service Worker registration successful with scope: ', registration.scope);
      }, function (err) {
        console.log('Service Worker registration failed: ', err);
      });
  });
}

在 webpack 配置中添加 CopyPlugin

const CopyPlugin = require('copy-webpack-plugin');

const config = {
  ...
  plugins: [
    ...
    new CopyPlugin({
      patterns: [
        // adjust 'service-worker.js' if your file is somewhere else
        { from: 'service-worker.js', to: '' }, 
      ],
    }),
  ]
}

module.exports = config;

只要在用户登录之前消费者应用程序的挂载上不存在 authToken,您很可能还需要从模块联合配置中删除遥控器。因此,遥控器的请求将在挂载时失败。要解决此问题,您需要使用以下命令加载遥控器动态远程容器 https://webpack.js.org/concepts/module-federation/#dynamic-remote-containers。该方法在此得到了完整的实现repo https://github.com/module-federation/module-federation-examples/tree/master/advanced-api/dynamic-remotes.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将自定义http标头添加到角度模块联合remoteEntry.js加载调用? 的相关文章

随机推荐

  • 检测应用程序的阶段(alpha、beta 或生产)

    我正在使用 cordova 开发一个 android 应用程序 我希望使用三个给定的阶段来逐步发布它 IT 测试的 Alpha 合作伙伴测试版 为其他人生产 但是 我正在使用 mixpanel 来跟踪一些用户输入 Mixpanel 需要一个
  • 在 EditText 中输入数据并响应,无需按 Enter 键

    我有一个带有侦听器的 editText edittext setOnKeyListener new OnKeyListener public boolean onKey View v int keyCode KeyEvent event I
  • 带有第二个 y 轴的 Seaborn 图

    i wanted to know how to make a plot with two y axis so that my plot that looks like this to something more like this by
  • 如何在xcode中创建数组键和值? [关闭]

    很难说出这里问的是什么 这个问题是含糊的 模糊的 不完整的 过于宽泛的或修辞性的 无法以目前的形式得到合理的回答 如需帮助澄清此问题以便重新打开 访问帮助中心 help reopen questions 我是一名新的 iPhone 开发者
  • 在 Mac OS X 中安装 Avro

    我正在查看 Avro RPC for Python 网址为https github com phunt avro rpc quickstart python https github com phunt avro rpc quickstar
  • EF Core 5.0 中的多对多关系是否可以配置为仅保留一个导航属性(在一侧)?

    我已使用以下代码配置了 DbContext EF Core 5 0 protected override void OnModelCreating ModelBuilder modelBuilder modelBuilder Entity
  • 如何使用 Chart.js 在堆积条形图中显示内联值?

    我正在使用 Chart js 库在堆叠条形图中显示一些值 但我正在努力找出如何显示条形图中的值 即 现在 我有以下代码 可以在条形顶部显示数字 但我想知道如何在条形内部显示它们 var numberWithCommas function x
  • 如何使用 UIImagePickerController CropRect

    我刚刚找到了一种方法来更改裁剪框的矩形 该裁剪框在捕获图像后出现UIImagePickerViewController 这可以在以下帮助下完成UIImagePickerControllerCropRect 但我不知道如何使用它 最初的裁剪框
  • 在 Python 的内置数字类型上,repr 和 str 总是相同吗?

    Are repr and strPython 内置数字类型相同 int bool float and complex 或者是否存在 深奥的 两者可能产生不同结果的情况 SO的相关问题 例如this one https stackoverfl
  • 在 iOS6 中处理手势识别器

    显然 当你有手势识别器和手势识别器时 iOS 6 会尝试自动处理这种情况 UIButton在同一个地方 用同一个手势被激活 当您想要单击按钮而不是激活手势识别器时 这种新的自动处理可以解决问题 但是产生了一个新问题当您希望手势识别器起作用时
  • 将多列传递给 groupby.transform

    据我所知 当您使用 DataFrame 列调用 groupby transform 时 该列将传递给转换数据的函数 但我无法理解的是如何将多个列传递给函数 people DataFrame np random randn 5 5 colum
  • OpenGL 的每个组件 alpha 通道?

    是否可以使用 OpenGL 对每个组件使用一个 alpha 通道 一个用于红色 一个用于绿色 一个用于蓝色 进行混合 如果没有 有哪些可能的解决方法 这不是直接支持的东西 不过 您自己实现起来相当容易 使用 3 通道 alpha 纹理渲染三
  • Espresso,查找对话框并将其关闭

    我试图找到一个对话框取消按钮并将其推入 Espresso UI 测试 但我做不到 这是我的代码 onView withId R id dialog close button check matches isDisplayed 最好的解决方案
  • 使用两个键执行自动完成 - Material UI with React

    当使用两个值之一搜索时 我试图自动完成输入 title and year 但是 它仅在我搜索时才有效title 当我搜索时year 它不显示任何选项 示例代码 export default function ComboBox return
  • 检查字符串是否多次包含子字符串[重复]

    这个问题在这里已经有答案了 要搜索字符串内的子字符串 我可以使用contains 功能 但是如何检查一个字符串是否多次包含子字符串呢 优化这一点 对我来说 知道有多个结果而不是有多少就足够了 尝试利用快速IndexOf and LastIn
  • 如何将函数转发/别名/委托给方法?

    我想将函数转发到另一个模块中的方法 而不重复所有类型注释 也不手动传递参数 我该怎么做 mod other mod static client other mod Client other mod Client new async fn s
  • 如何获得 GTK 中的默认颜色?

    Context 在 GTK 3 中 人们可以设置自己的主题 甚至默认主题 Adwaita 也提供两种变体 浅色和深色 当我编写自己的小部件 用Python 时 我需要获取这些颜色以避免在黑色上绘制黑色或在白色上绘制白色 Question 如
  • 如何编辑 .csproj 文件

    当我使用 NET Framework 4 0 MSBUILD EXE 文件编译 csproj 文件时 出现错误 在 website01 csproj 的当前上下文中找不到 lable01 实际上 我需要添加每个 ASP NET 页面及其代码
  • 如何在 Mongoose 中设置文档创建的 TTL 日期?

    我正在尝试做一个promoCodeMongoose 中的架构 创建时 我需要能够设置促销代码的到期日期 促销代码不一定相同TTL 我在看这个问题 https stackoverflow com questions 14597241 sett
  • 如何将自定义http标头添加到角度模块联合remoteEntry.js加载调用?

    我有一个主机应用程序和一些微前端应用程序都是 Angular 15 我用过 angular architects module federation 15 0 3 一切工作正常 除了我无法拦截加载 mfe 应用程序的 remoteEntry