跨域问题(....as been blocked by CORS policy)

朱雀 2023-02-09 14:17 78阅读 0赞

前端报错信息
在这里插入图片描述

跨越报错的原因

在这里插入图片描述

跨越流程

跨域会发送2次请求,

  1. 是预检请求, (OPTIONS 方式发送)
  2. 是发送真实请求
    在这里插入图片描述

跨越解决

方式一:
在这里插入图片描述

方式二:
在这里插入图片描述

代码示例:

本人是给网关添加一个过滤器,解决所有的跨域问题(也可以给具体某个服务添加跨域)

  1. @Configuration
  2. public class CorsConfig {
  3. // Spring 为我们提供了一个CorsFiler 我们只需要把他放到容器来即可
  4. @Bean
  5. public CorsWebFilter corsWebFilter() {
  6. // 跨域的配置信息 springframework.web.cors.reactive 包下的
  7. UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
  8. CorsConfiguration corsConfiguration = new CorsConfiguration();
  9. // 支持哪些来源的请求
  10. corsConfiguration.addAllowedOrigin("*");
  11. // 支持的请求头
  12. corsConfiguration.addAllowedHeader("*");
  13. // 支持哪些请求方式
  14. corsConfiguration.addAllowedMethod("*");
  15. // 是否允许携带 cookie
  16. corsConfiguration.setAllowCredentials(true);
  17. // 注册跨域的配置信息,任意路径下
  18. corsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
  19. return new CorsWebFilter(corsConfigurationSource);
  20. }
  21. }

注意:服务端或者网关只能有其中一个配置跨域配置,否则会报错:
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,78人围观)

还没有评论,来说两句吧...

相关阅读