CorsConfig 跨域
分析次报错是因为 服务访问的时候被判定为断域,
跨域的打头兵,其实跨域还么有发出去
跨域请求的流程: 浏览器 先会给服务器发送一个 预检请求 ,服务器 返回同意不同意 ,同意的话 浏览器 在发送真实的请求 ,服务再返回响应成功是否
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS
跨域代码:
package com.atguigu.gulimall.gateway.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.reactive.CorsConfigurationSource; import org.springframework.web.cors.reactive.CorsWebFilter; import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; import org.springframework.web.server.ServerWebExchange; @Configuration public class GulimallCorsConfiguration { //写跨域相关的代码 @Bean //注入到容器中 public CorsWebFilter corsWebFilter() { //CorsConfigurationSource 他的实现是 UrlBasedCorsConfigurationSource UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration corsConfiguration = new CorsConfiguration(); //1.配置跨域 容许那些头跨域 corsConfiguration.addAllowedHeader("*"); //2.容许那些请求方式跨域 get/post.. corsConfiguration.addAllowedMethod("*"); //3.容许那些请求来源跨域 corsConfiguration.addAllowedOrigin("*"); //4.是否容许携带 酷开 corsConfiguration.setAllowCredentials(true); //代表任何路径 全部 corsConfiguration 配置的相关参数 //registerCorsConfiguration 注册跨域的配置 source.registerCorsConfiguration("/**",corsConfiguration); /*CorsConfigurationSource corsConfigurationSource = new CorsConfigurationSource() { @Override public CorsConfiguration getCorsConfiguration(ServerWebExchange exchange) { return null; } } */ return new CorsWebFilter(source); } }
理解:
大体意思为 :
Access to XMLHttpRequest at 'http://localhost:88/api/sys/login' from origin 'http://localhost:8001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
http://localhost:88/api/sys/login 访问到 http://localhost:8001的时候 请求被堵塞了 "cors"(跨域) Access-Control-Allow-Origin' 访问 控制 请求 来源 浏览器为了安全默认拒绝这些跨域的请求 怎么解决: 浏览器会检查头 , Access-Control-Allow-Origin 解决跨域的办法