后台跨域, nginx跨域,nginx跨域无效

发布时间 2023-11-17 11:41:35作者: qukaige

nginx跨域配置

location /api {
    # 允许跨域请求的域,* 代表所有。如果是特定的域名,应该将 * 替换为确切的域名。
    add_header 'Access-Control-Allow-Origin' '*' always;
    # 允许带上 cookie 请求
    add_header 'Access-Control-Allow-Credentials' 'true' always;
    # 允许请求的方法,比如 GET/POST/PUT/DELETE,* 表示允许所有方法
    add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
    # 允许请求的 header,* 表示允许所有头信息,也可以根据需要指定允许的头信息
    add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type, Origin, X-Requested-With, Accept' always;

    # 如果是预检请求(OPTIONS),直接返回 200,不再执行 proxy_pass
    if ($request_method = 'OPTIONS') {
        add_header 'Content-Length' 0;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        return 204;
    }

    # 代理到后端服务
    proxy_pass http://111:8080/api;
}

 

当nginx配置无效请修改后台跨域配置

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
@Configuration
public class CorsConfig {
    @Bean
    public CorsWebFilter  corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 配置跨域
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 允许哪个请求头
        corsConfiguration.addAllowedHeader("*");
        // 允许哪个方法进行跨域
        corsConfiguration.addAllowedMethod("*");
        // 允许哪个请求来源进行跨域
        // corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedOriginPattern("*");
        // 是否允许携带cookie进行跨域
        corsConfiguration.setAllowCredentials(true);

        source.registerCorsConfiguration("/**",corsConfiguration);
        return new CorsWebFilter(source);
    }
}