webpack 部署时,带模块联合的Angular 微型前端抛出CORS错误

oknrviil  于 2023-03-02  发布在  Webpack
关注(0)|答案(1)|浏览(162)

我有一个主机和两个微前端(都是Angular 14)。这在本地开发中工作得很好。最后我将它们容器化并在Docker中运行。我的主机容器试图从两个微前端容器中获取remoteEntry.js,但在这样做时出现了CORS错误。
请建议如何克服这一点。
CORS策略已阻止从源"http://localhost:5000"访问位于"http://localhost:3000/remoteEntry.js"的脚本:请求的资源上不存在"Access-Control-Allow-Origin"标头。
我的webpack.config.js的两个mfe之一

const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
const mf = require("@angular-architects/module-federation/webpack");
const path = require("path");
const share = mf.share;

const sharedMappings = new mf.SharedMappings();
sharedMappings.register(
  path.join(__dirname, '../../tsconfig.json'),
  [
    /* mapped paths to share */
    '@shared'
  ]);

module.exports = {
  devServer: {
    allowedHosts: 'all',
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
      "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
    }
  },
  output: {
    uniqueName: "medicalcoding",
    publicPath: "auto"
  },
  optimization: {
    runtimeChunk: false
  },
  resolve: {
    alias: {
      ...sharedMappings.getAliases(),
    }
  },
  experiments: {
    outputModule: true
  },
  plugins: [
    new ModuleFederationPlugin({
      library: { type: "module" },

      // For remotes (please adjust)
      name: "medicalcoding",
      filename: "remoteEntry.js",
      exposes: {
        './Module': './projects/medicalcoding/src/app/app.module.ts',
      },

      // For hosts (please adjust)
      // remotes: {
      //     "mainapp": "http://localhost:5000/remoteEntry.js",
      //     "paymentposting": "http://localhost:4200/remoteEntry.js",

      // },

      shared: share({
        "@angular/core": { singleton: true, strictVersion: true, requiredVersion: 'auto' },
        "@angular/common": { singleton: true, strictVersion: true, requiredVersion: 'auto' },
        "@angular/common/http": { singleton: true, strictVersion: true, requiredVersion: 'auto' },
        "@angular/router": { singleton: true, strictVersion: true, requiredVersion: 'auto' },

        ...sharedMappings.getDescriptors()
      })

    })
    , sharedMappings.getPlugin()
  ],
};
ulmd4ohb

ulmd4ohb1#

从技术上讲,不同的端口是不同的域。因此,即使这些微前端来自本地主机,它们的端口也是不同的,必须在服务器中列入白名单。您没有提供有关服务器部分的信息,因此很难说您应该在哪里以及确切地更改什么,因为每个实现都是不同的。
基本上,您必须在服务器中将您的调用域列入白名单。
既然你写的这是一个有Angular 的应用,我猜你是用Webpack来服务这些应用的,在你的devServer中,你可以设置CORS头:

devServer: {
  ...,
  headers: {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
    "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
  }
},

相关问题