Jsonp
#允许跨域请求的域,*代表所有
response.setHeader("Access-Control-Allow-Origin", "*");
// 指定特定域名可以访问
response.setHeader("Access-Control-Allow-Origin", "http:localhost:8080/");
#允许带上cookie请求
response.setHeader("Access-Control-Allow-Credentials","true");
#允许请求的方法,比如 GET/POST/PUT/DELETE
response.setHeader("Access-Control-Allow-Methods","*");
#允许请求的header
response.setHeader("Access-Control-Allow-Headers","*");
SpringBoot Cors
@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);
}
}
Nginx跨域配置支持
#允许跨域请求的域,*代表所有
add_header 'Access-Control-Allow-Origin' *;
#允许带上cookie请求
add_header 'Access-Control-Allow-Credentials' 'true';
#允许请求的方法,比如 GET/POST/PUT/DELETE
add_header 'Access-Control-Allow-Methods' *;
#允许请求的header
add_header 'Access-Control-Allow-Headers' *;