You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Vite中消费外部联邦模块时遭遇CORS问题

问题分析与解决方案

你的CORS报错核心逻辑搞反了:你当前在Vite里配置的server.headers、preview.headers是给本地服务(http://localhost:5005)设置响应头,允许其他域名访问你的本地服务,但现在的问题是本地服务要请求远程的remoteEntry.js,需要远程服务(http://www.example.com)返回允许http://localhost:5005的CORS头。

浏览器直接访问http://www.example.com/remoteEntry.js能打开,是因为此时浏览器的页面域名就是该远程域名,不存在跨域场景,所以不会触发CORS校验,和本地项目跨域请求的情况完全不同。


解决方案分两种情况:

1. 远程服务由你维护

直接修改远程服务的配置,让它在返回remoteEntry.js时添加允许本地域名的CORS头:

  • 如果远程也是Vite项目,在它的vite.config.js里添加:
    export default defineConfig({
      server: {
        headers: {
          "Access-Control-Allow-Origin": "http://localhost:5005",
          // 生产环境不建议用*,仅测试时可临时使用
          // "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Methods": "GET, OPTIONS"
        }
      },
      preview: {
        headers: {
          "Access-Control-Allow-Origin": "http://localhost:5005",
          "Access-Control-Allow-Methods": "GET, OPTIONS"
        }
      }
    })
    
  • 如果远程是Nginx部署的,在Nginx配置里添加:
    location /remoteEntry.js {
      add_header Access-Control-Allow-Origin http://localhost:5005;
      add_header Access-Control-Allow-Methods GET,OPTIONS;
    }
    

2. 远程服务无法修改(第三方服务)

用Vite的代理功能绕开CORS:把对远程的请求代理成本地路径,这样浏览器会认为是同域请求,不会触发CORS校验。

修改你的Vite配置:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import federation from "@originjs/vite-plugin-federation";

export default defineConfig({
  plugins: [
    react(),
    federation({
      name: 'host-app',
      // 改为代理后的本地路径
      remotes: {
        remoteApp: "/remote-proxy/remoteEntry.js",
      },
      shared: ['react', 'react-dom']
    })
  ],
  preview: {
    host: 'localhost',
    port: 5005,
    strictPort: true,
    // 添加预览环境代理配置
    proxy: {
      '/remote-proxy': {
        target: 'http://www.example.com',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/remote-proxy/, '')
      }
    }
  },
  build: {
    target: 'esnext'
  },
  server: {
    // 添加开发环境代理配置
    proxy: {
      '/remote-proxy': {
        target: 'http://www.example.com',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/remote-proxy/, '')
      }
    }
  }
})

配置完成后,本地项目请求/remote-proxy/remoteEntry.js时,Vite会自动把请求转发到http://www.example.com/remoteEntry.js,并处理跨域相关头,浏览器就不会再报CORS错误了。


内容的提问来源于stack exchange,提问作者John Z

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 18:02:33