DEBUG.WIKI
阿里云;从建站到云上业务;云服务器 · 数据库 · 对象存储;查看产品 →
PanstarCloud:部署应用,接入 AI,云服务器与 AI 网关
IPPeak:从目标地区访问网页,住宅代理、SEO 监测、广告验证

解决浏览器 CORS 跨域报错 No 'Access-Control-Allow-Origin' header is present 修复

排查前端 Ajax/Fetch 请求跨域被浏览器拦截提示 No Access-Control-Allow-Origin header is present 错误,掌握后端与 Nginx 响应头配置规范。

问题现象

前端网页通过 JavaScript fetch() 或 axios 调用后端跨域接口时,控制台抛出红色错误,页面无法获取数据:

Access to fetch at 'https://api.example.com/users' from origin 'https://web.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

网络面板显示该请求状态为 (failed) 或返回了响应但被浏览器安全沙箱直接隐藏。

触发根因

浏览器的同源策略(Same-Origin Policy, SOP)规定:协议、域名、端口三者只要有一个不同,即属于跨域请求。

  1. 跨域资源共享(CORS)机制:浏览器在发起跨域网络请求时,会在请求头中自动注入 Origin: https://web.example.com;
  2. 服务端未返回响应头:服务端在 HTTP 响应中必须显式返回 Access-Control-Allow-Origin 告知浏览器允许该源访问;
  3. 如果后端未配置 CORS 中间件,或者后端发生 500 异常提前退出导致全局响应头未被注入,浏览器直接对前端代码隐藏返回数据。

解决步骤

1. 在后端框架中启用标准化 CORS 中间件

在 Node.js (Express) 中:

const cors = require('cors');
app.use(cors({
  origin: 'https://web.example.com',
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));

在 Spring Boot 中:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("https://web.example.com")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS");
    }
}

2. 在反向代理(Nginx)层统一注入 CORS 头

如果不想在代码中处理,可在 Nginx 中统一注入:

location / {
    add_header 'Access-Control-Allow-Origin' 'https://web.example.com' always;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;

    if ($request_method = 'OPTIONS') {
        # 预检请求直接返回 204
        return 204;
    }

    proxy_pass http://backend_upstream;
}

注意:必须带上 always 参数,确保即使后端返回 4xx/5xx 错误时,该跨域头也能正常下发给前端。

验证确认

在浏览器控制台重新发起请求,观察 Response Headers 中成功包含:

Access-Control-Allow-Origin: https://web.example.com

前端正常拿到 JSON 数据,控制台红叉消失,跨域阻断成功解决。