您可以使用 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.