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

Single SPA微前端LOADING_SOURCE_CODE报错及CORS跨域问题求助

解决single-spa子应用跨域CORS加载错误问题

你遇到的是典型的跨域资源共享(CORS)问题,根源是子应用服务器未配置允许根应用域名的跨域请求头,以下是几种可行的解决方式:

1. 配置子应用服务器的CORS响应头

这是最直接的解决方案,在子应用部署的服务器(如Nginx、Apache)中添加跨域允许规则:

Nginx 配置示例

在子应用的Nginx站点配置中添加:

location / {
    # 允许根应用域名跨域
    add_header Access-Control-Allow-Origin https://test.com;
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
    
    # 处理浏览器预检OPTIONS请求,直接返回204
    if ($request_method = OPTIONS) {
        return 204;
    }
}

生产环境建议指定具体允许的域名(如https://test.com),而非通配符*,避免安全风险。

Apache 配置示例

在子应用的.htaccess文件或httpd.conf中添加:

Header set Access-Control-Allow-Origin "https://test.com"
Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
Header set Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range"

# 处理预检OPTIONS请求
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=204,L]

2. 在根应用服务器配置反向代理

如果无法修改子应用服务器的配置,可以通过根应用服务器反向代理子应用资源,避免跨域:

以Nginx为例,在根应用的Nginx配置中添加反向代理规则:

location /Common/ {
    proxy_pass https://external.com/Common/;
    proxy_set_header Host external.com;
    proxy_set_header X-Real-IP $remote_addr;
}

然后修改single-spa中注册子应用的entry配置,将原有的https://external.com/Common/main.js替换为/Common/main.js,此时请求会通过根应用服务器转发到子应用,不存在跨域问题。

3. 开发环境临时处理

如果是开发阶段遇到该问题,可以通过webpack devServer配置添加跨域头:
在子应用的webpack.config.js中添加:

module.exports = {
  // ...其他配置
  devServer: {
    headers: {
      'Access-Control-Allow-Origin': 'https://test.com',
      'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
      'Access-Control-Allow-Headers': '*'
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 00:17:27