跨域
本文最后更新于 952 天前,其中的信息可能已经有所发展或是发生改变。

Nginx

server {
    listen       80;
    server_name  www.tenbeggar.com;
    root         /usr/share/nginx/html;
    location / {
        proxy_pass http://localhost:8888/;
        add_header Access-Control-Allow-Credentials true;	#允许凭证
        add_header Access-Control-Allow-Origin * always;	#允许的域
        add_header Access-Control-Allow-Methods *;			#允许的请求方式
        add_header Access-Control-Allow-Headers *;			#允许的请求头
        if ($request_method = 'OPTIONS') {
            return 204;
        }
    }
    error_page 404 /404.html;
        location = /40x.html {
    }
    error_page 500 502 503 504 /50x.html;
        location = /50x.html {
    }
}

Spring Boot

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;
import java.time.Duration;
import java.util.Collections;
@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOriginPatterns(Collections.singletonList("*"));//允许的域
        config.setAllowCredentials(true);//允许凭证
        config.addAllowedHeader(CorsConfiguration.ALL);//允许的请求头
        config.addAllowedMethod(CorsConfiguration.ALL);//允许的请求方式
        config.setMaxAge(Duration.ofHours(3));//有效时间
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}
如果觉得本文对您有帮助,记得收藏哦~
上一篇
下一篇