{T}

解决跨域

浏览器为了用户的安全,仅允许向 同域名、同端口 的服务器发送请求

把域名、端口改成相同的

让服务器告诉浏览器:允许跨域(返回 cross-origin-allow 响应头)

网关支持 Nginx

nginx 配置跨域

nginx
location ^~ /api/ {
    # 开启反向代理 $http_origin 内置变量
    proxy_pass http://127.0.0.1:8080/api/; 
    add_header 'Access-Control-Allow-Origin' $http_origin;
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers '*';
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Origin' $http_origin;
        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';
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        add_header 'Content-Length' 0;
        return 204;
    }
}

修改后端服务

  1. 配置 @CrossOrigin(origins={ },methods={ }) 注解
  2. 添加 web 全局请求拦截器
  3. 定义新的 corsFilter Bean,参考:https://www.jianshu.com/p/b02099a435bd

CORS

CORS (Cross-Origin Resource Sharing) 是一种允许或限制某些跨源请求的机制。服务器通过设置 HTTP 响应头 Access-Control-Allow-* 来控制跨域访问

java
@Configuration
public class WebMvcConfg implements WebMvcConfigurer {

  // 当 Credentials 为 true 时,Origin 不能为星号,需为具体的 ip 地址【如果接口不带 cookie,ip 无需设成具体 ip】
  @Override
  public void addCorsMappings(CorsRegistry registry) {
    //设置允许跨域的路径
    registry.addMapping("/**")
      .allowedOrigins("http://localhost:9527", "http://127.0.0.1:9527")
      .allowCredentials(true) // 是否允许证书 不再默认开启
      .allowedMethods("*")  // 设置允许的方法
      .maxAge(3600);  // 跨域允许时间
  }
}

或者

java
package com.xiaoye.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {

  public CorsConfig() {
  }

  @Bean
  public CorsFilter corsFilter() {
    // 1. 添加 cors 配置信息
    CorsConfiguration config = new CorsConfiguration();
    config.addAllowedOrigin("http://localhost:8080");
    config.addAllowedOrigin("http://shop.z.mukewang.com:8080");
    config.addAllowedOrigin("http://center.z.mukewang.com:8080");
    config.addAllowedOrigin("http://shop.z.mukewang.com");
    config.addAllowedOrigin("http://center.z.mukewang.com");
    config.addAllowedOrigin("*");

    // 设置是否发送 cookie 信息
    config.setAllowCredentials(true);

    // 设置允许请求的方式
    config.addAllowedMethod("*");

    // 设置允许的 header
    config.addAllowedHeader("*");

    // 2. 为 url 添加映射路径
    UrlBasedCorsConfigurationSource corsSource = new UrlBasedCorsConfigurationSource();
    corsSource.registerCorsConfiguration("/**", config);

    // 3. 返回重新定义好的 corsSource
    return new CorsFilter(corsSource);
  }
}

代理服务器

通过在服务器端设置一个代理服务器,将请求转发到目标服务器,然后返回结果给客户端。

java
// 创建代理服务器的伪代码
public String proxyRequest(String targetUrl, String proxyUrl) {
  // 发送请求到目标服务器
  // 获取响应
  // 将响应转发回客户端
  return responseContent;
}

修改响应头

在服务器端的每个请求后手动设置允许跨域的响应头

java
// 在每个请求处理后设置响应头
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");

注解 @CrossOrigin

在 Spring 或 Spring Boot 应用程序中,可以使用 @CrossOrigin 注解来允许跨域

java
@RestController
@CrossOrigin(origins = "http://example.com")
public class MyController {
  @GetMapping("/api/data")
  public ResponseEntity<?> getData() {
    // 返回数据
  }
}

版本差异(CORS 解决 → Spring Boot 3.5.x)

特性旧方案当前方案
全局配置WebMvcConfigurer addCorsMappings不变(Boot 3.x 中仍用 addCorsMappings)
注解@CrossOrigin不变;支持按方法/类级配置
网关跨域后端各自处理网关统一处理(Spring Cloud Gateway CorsWebFilter)
敏感场景允许 credentialsCookie 需 SameSite=None + Secure;推荐 token 方案

CORS 机制(同源策略、预检 OPTIONS、响应头)不随版本变化;Boot 3.x 配置方式与 2.x 一致,注意 Spring Security 6 需在过滤器链中显式放行预检请求。