YEGUO

跨域解决

|
|
3 min read

1、nginx配置代理解决跨域

location / {
    # WebSocket support
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    
    # Other configurations...
    add_header 'Access-Control-Allow-Origin' 'https://example.com';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT';
    add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
    add_header 'Access-Control-Allow-Credentials' 'true' always;
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' 'https://example.com';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT';
        add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
        add_header 'Access-Control-Allow-Credentials' 'true' always;
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        return 204;
    }
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
}

2、注解配置

@CrossOrigin(origins = { "http://xxx.com/"}, methods = { RequestMethod.DELETE },allowCredentials = "true")
  • origins: 同样是指定允许跨域请求的源,即允许访问资源的域名。在这里,同样只允许来自 “http://xxx.com” 的跨域请求。
  • methods: 允许请求的方法。
  • allowCredentials: 指定是否允许发送身份验证信息(例如 cookie)到目标域。在这里设置为 true,表示允许发送身份验证信息。

3、Web全局请求拦截器配置

@Configuration
public class WebMvcConfg implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //设置允许跨域的路径
        registry.addMapping("/**")
                //设置允许跨域请求的域名 
                //当**Credentials为true时,**Origin不能为星号,需为 具体的ip地址【如果接口不带cookie,ip无需设成具体ip】 
                .allowedOrigins(
            	"http://127.0.0.1:9527", 
           		"http://127.0.0.1:8082",
                "http://127.0.0.1:8083")
                //是否允许证书 不再默认开启 
                .allowCredentials(true) 
                //设置允许的方法 
                .allowedMethods("*")
                //跨域允许时间 
                .maxAge(3600);
    }
    // 或
     @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            //当 Credentials为true时,Origin不能为星号,需为具体的ip地址【如果接口不带cookie,ip无需设成具体ip】,使用allowedOriginPatterns可以带*
                .allowedOriginPatterns("*")
           		 //设置允许的方法 
                .allowedMethods("*")
               	//指定是否允许发送身份验证信息(例如 cookie)到目标域
                .allowCredentials(true)
             	//跨域允许时间 
            	.maxAge(3600); // 允许携带身份验证信息
	}

}

© 2023 - 2026 YEGUO