1.后端服务开启跨域
//第一种
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedHeaders(CorsConfiguration.ALL)
.allowedMethods(CorsConfiguration.ALL)
.allowCredentials(true)
.maxAge(3600); // 1小时内不需要再预检(发OPTIONS请求)
}
}
//第二种
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true); //支持cookie 跨域
config.setAllowedOrigins(Arrays.asList("*"));
config.setAllowedHeaders(Arrays.asList("*"));
config.setAllowedMethods(Arrays.asList("*"));
config.setMaxAge(300L);//设置时间有效
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
2.nginx开启跨域
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
#这里2种写法
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Origin $http_origin;
#add_header "Access-Control-Allow-Origin" "*"; #允许来自所有的访问地址
#add_header "Access-Control-Allow-Methods" "GET, PUT, POST, DELETE, OPTIONS"; #支持请求方式
location = / {
root html;
index index.html index.htm;
}
}
}
总结:
1.前端配置跨域 无论后台及nginx 配不配 都可以跨域
2.后台配置跨域 或nginx 配置跨域 前台不配 都可以跨域
3.后台与 nginx 同时配置跨域 前台不配 不可以跨域