[Problem Solving] Cross-domain image cross-domain problem has been blocked by CORS policy No-Access-Control-Allow-Origin

Article directory


Environmental background of this blog: Under the JAVA project, there is a cross-domain problem with the image during joint debugging of the front-end and back-end, and the error has been blocked by CORS policy No-Access-Control-Allow-Origin.

CORS cross domain

CORS is a W3C standard, whose full name is "Cross-origin resource sharing".

It allows the browser to issue XMLHttpRequest requests to cross-origin servers, thus overcoming the limitation that AJAX can only be used from the same origin. It is a restriction on ajax requests. CORS has no cross-domain restrictions on static resources.

General situation of cross-domain problems:
1. The domain names are different www.baidu.com and www.qq.com
2. The ports are different www.baidu.com:8080 and www.baidu.com:8081
3. The second-level domain names are different test.baidu. com and other.baidu.com
4. http and https

solution

Cross-domain problems are actually very common, and you can directly add the CorsConfig configuration class. The browser will carry some header information in the request. We use this to determine whether to allow it to cross domain, and then add this information to the request header. This can be done directly using filters.

Access-Control-Allow-Origin: Which domain name is allowed for cross-domain, it is a specific domain name or * (representing any domain name) Access-Control-
Allow-Credentials: Whether to allow cookies to be carried. By default, CORS does not carry cookies, so you need to Set this value to true

It is equivalent to intercepting all requests at the same time, then using CorsFilter to implement cross-domain logic, and finally returning a new CorsFilter.
CorsFilter is a cross-domain filter of CORS that SpringMVC has encapsulated, which internally covers the decision logic involved in http requests.

@Configuration
public class CorsConfig {
    
    
    @Bean
    public CorsFilter corsFilter() {
    
    
		//创建一个可添加CORS配置信息  
        CorsConfiguration config = new CorsConfiguration();
        //允许的域,若使用addAllowedOrigin("*");会导致cookie失效,要将*换成域名
        config.addAllowedOriginPattern("*");
        //是否发送cookie信息
        config.setAllowCredentials(true);
        //允许的请求方式
        config.addAllowedMethod("*");
        //允许的头信息
        config.addAllowedHeader("*");

		//添加映射路径,这儿拦截所有请求
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);

        return new CorsFilter(configSource);
    }
}

Reference: https://zhuanlan.zhihu.com/p/66484450
https://zhuanlan.zhihu.com/p/121042077

Guess you like

Origin blog.csdn.net/weixin_44436677/article/details/127946155