其他分享
首页 > 其他分享> > 报错:跨域问题解决 No ‘Access-Control-Allow-Origin‘ header is present on the requested resource.

报错:跨域问题解决 No ‘Access-Control-Allow-Origin‘ header is present on the requested resource.

作者:互联网

报错:

Access to XMLHttpRequest at 'http://127.0.0.1:8088/user/list' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
xhr.js?b50d:178 GET http://127.0.0.1:8088/user/list net::ERR_FAILED

在学习前后端分离开发的过程中,遇到这个报错是非常正常的,当然也是比较好解决的问题,莫非就是前端项目使用了一个端口,后端项目使用了一个端口,但是其实同一个ip,但是不同端口之间也不能直接获取信息的,那么就要解决它。

先说一下情况,当前我是一个Spring Boot项目,版本是2.x版本。

想要更多了解的话,你可以看一下我三年前写的一篇文章,这样子解决也行,如果是自己学习的话:SpringBoot+JSON+AJAX+ECharts+Fiddler实现前后端分离开发可视化(进阶篇)
直接看菜单部分即可,通过软件进行端口转发,但这其实还是有点麻烦的,而且不够灵活。

Spring Boot项目中,解决非常简单,新建一个配置类,然后用注解注入即可:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedHeaders(CorsConfiguration.ALL)
                .allowedMethods(CorsConfiguration.ALL)
                .allowCredentials(true)
                .maxAge(3600); // 1小时内不需要再预检(发OPTIONS请求)
    }
}

重启项目,就可以解决了!

当然,如果你还没解决,还有一个常见的错误,那就是,你前端的请求路径写错了,务必要小心!!!


如果是Spring Cloud项目,使用的是Gateway网关,可直接在GatewayApplication加上以下内容即可:

	@Bean
	public CorsWebFilter corsFilter() {
		CorsConfiguration config = new CorsConfiguration();

		config.setAllowCredentials(Boolean.TRUE);
		config.addAllowedMethod("*");
		config.addAllowedOrigin("*");
		config.addAllowedHeader("*");
		config.setMaxAge(3600L);

		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
		source.registerCorsConfiguration("/**", config);

		return new CorsWebFilter(source);
	}

加上了就可以删掉上面的 CorsConfig了,如果你有加了的话。

标签:Control,CorsConfiguration,端口,Access,报错,解决,new,config
来源: https://blog.51cto.com/u_12564104/2896737