Jsonp

  1. #允许跨域请求的域,*代表所有
  2. response.setHeader("Access-Control-Allow-Origin", "*");
  3. // 指定特定域名可以访问
  4. response.setHeader("Access-Control-Allow-Origin", "http:localhost:8080/");
  5. #允许带上cookie请求
  6. response.setHeader("Access-Control-Allow-Credentials","true");
  7. #允许请求的方法,比如 GET/POST/PUT/DELETE
  8. response.setHeader("Access-Control-Allow-Methods","*");
  9. #允许请求的header
  10. response.setHeader("Access-Control-Allow-Headers","*");

SpringBoot Cors

  1. @Configuration
  2. public class CorsConfig {
  3. public CorsConfig() {
  4. }
  5. @Bean
  6. public CorsFilter corsFilter() {
  7. // 1. 添加cors配置信息
  8. CorsConfiguration config = new CorsConfiguration();
  9. config.addAllowedOrigin("http://localhost:8080");
  10. config.addAllowedOrigin("http://shop.z.mukewang.com:8080");
  11. config.addAllowedOrigin("http://center.z.mukewang.com:8080");
  12. config.addAllowedOrigin("http://shop.z.mukewang.com");
  13. config.addAllowedOrigin("http://center.z.mukewang.com");
  14. config.addAllowedOrigin("*");
  15. // 设置是否发送cookie信息
  16. config.setAllowCredentials(true);
  17. // 设置允许请求的方式
  18. config.addAllowedMethod("*");
  19. // 设置允许的header
  20. config.addAllowedHeader("*");
  21. // 2. 为url添加映射路径
  22. UrlBasedCorsConfigurationSource corsSource = new UrlBasedCorsConfigurationSource();
  23. corsSource.registerCorsConfiguration("/**", config);
  24. // 3. 返回重新定义好的corsSource
  25. return new CorsFilter(corsSource);
  26. }
  27. }

Nginx跨域配置支持

  1. #允许跨域请求的域,*代表所有
  2. add_header 'Access-Control-Allow-Origin' *;
  3. #允许带上cookie请求
  4. add_header 'Access-Control-Allow-Credentials' 'true';
  5. #允许请求的方法,比如 GET/POST/PUT/DELETE
  6. add_header 'Access-Control-Allow-Methods' *;
  7. #允许请求的header
  8. add_header 'Access-Control-Allow-Headers' *;