跨域访问问题及解决
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.
-
,同协议,同域名,同端口被称为同域,浏览器不允许跨域请求的情况(非简单请求)(localhost:本机 127.0.0.1:本机),在访问路径’/hello’之前的这段字符,如果改变了,都被视为跨域
- https://localhost:8080/hello 访问 https://localhost:80/hello
- https://localhost:8080/hello 访问 https://127.0.0.1:8080/hello
- https://localhost:8080/hello 访问 http://localhost:8080/hello
- 等等
-
解决跨域请求
-
问题一,跨域不成功
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.
POST http://localhost:88/api/sys/login net::ERR_FAILED
Uncaught (in promise) Error: Network Error
at createError (createError.js?16d0:16)
at XMLHttpRequest.handleError (xhr.js?ec6c:87) -
解决办法:
-
1、跨域文档说明https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS
-
2、在网关编写跨域请求的配置文件,由网关统一跨域请求,再进行响应
-
3、需要用到CorsWebFilter类,这个类可以用来配置跨域信息的类,在配置文件中加入bean
-
CorsWebFilter构造函数没有无参构造,所以要new 一个CorsConfigurationSource
-
CorsConfigurationSource是以个接口,ctrl+h查看实现类,可以得知只有一个UrlBasedCorsConfigurationSource类实现了这个接口
-
-
- UrlBasedCorsConfigurationSource有三个方法,我们需要用到registerCorsConfiguration方法,注册跨域配置信息,所以我们还需要new一个CorsConfiguration
-
-
corsConfiguration的就是配置信息了,为http的请求/响应信息,我们可以按需设置
-
编写解决跨域代码
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;
@Configuration
public class CorsConfig {
@Bean
public CorsWebFilter corsWebFilter(){
//构造CorsWebFilter需要传入一个CotsConfigurationSorcery接口
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//跨域文件配置
CorsConfiguration corsConfiguration = new CorsConfiguration();
//配置跨域请求,
//允许哪些头进行请求跨域
corsConfiguration.addAllowedHeader("*");
//允许哪些方法进行请求跨域
corsConfiguration.addAllowedMethod("*");
//允许哪些源进行请求跨域
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.setAllowCredentials(true);
//注册跨域信息
source.registerCorsConfiguration("/**",corsConfiguration);
//构造source信息
return new CorsWebFilter(source);
}
}
-
问题解决
-
问题二,在跨域处理过程中,写了多分跨域处理的代码,这种问题只要删除其中一个跨域处理的代码即可