Test cross-domain requests online

  1. Open your browser, open a web page (such as Nuggets), and press F12 to bring up the Developer tools. The Google Browser Developer Tools interface is as follows:

  1. Enter the following code on Console:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://xxx.com/common/listCity');
xhr.send(null);
xhr.onload = function(e) {
    var xhr = e.target;
    console.log(xhr.responseText);
}
Copy the code

  1. Enter to run the code, and if a cross-domain problem occurs, the following message will be prompted

Note that the gold digging url is HTTPS, you can only debug the HTTPS interface, if you want to debug HTTP, you need to open an HTTP url

JAVA handles cross-domain

The WebMvcConfigurerAdapter configures the cross-domain that joins the Cors

import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class CorsConfig extends WebMvcConfigurationSupport { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**"); }}Copy the code

Integrated HandlerInterceptorAdapter interceptors

@Component public class CorsInterceptor extends HandlerInterceptorAdapter { private final Logger logger = LoggerFactory.getLogger(CorsInterceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { response.setHeader("Access-Control-Allow-Origin",request.getHeader("origin")); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS"); response.setHeader("Access-Control-Max-Age", "86400"); response.setHeader("Access-Control-Allow-Headers", "*"); / / if the end is the OPTIONS request if (HttpMethod. OPTIONS. The toString (). The equals (request) getMethod ())) { response.setStatus(HttpStatus.NO_CONTENT.value()); return false; } return true; }}Copy the code
@Configuration public class WebMvcConfig extends WebMvcConfigurationSupport{ @Recourse private CorsInterceptor corsInterceptor; Public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(corsInterceptor); }}Copy the code

Create a filter to resolve cross-domain

@Component
public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}
Copy the code

CorsFilter configuration for SpringBoot (recommended)

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig(a) {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // Allow any domain name
        corsConfiguration.addAllowedOrigin("*");
        // Allow any headers
        corsConfiguration.addAllowedHeader("*");
        // Allow any method
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter(a) {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        / / register
        source.registerCorsConfiguration("/ * *", buildConfig());
        return newCorsFilter(source); }}Copy the code

The problem

  1. Configure multiple cross-domains
Access to XMLHttpRequest at 'http://shidemo.vaiwan.com/api/activityOrder/listStoreOrder' from origin 'http://api.demo.cn' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values '*, http://api.demo.cn', but only one is allowed.
Copy the code

Multiple cross-domain processes are configured in the code, but only one of them is allowed. Remove any of them

  1. HTTPS web pages cannot debug HTTP
Mixed Content: The page at 'https://juejin.cn/user/3861140566970237/posts' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://shidemo.vaiwan.com/api/area/cityList?cityChar=&cityId=&cityName=&provinceId='. This request has been blocked; the content must be served over HTTPS.
Copy the code

  1. An insecure certificate

reference

Nine Cross-domain Implementation Principles (Full version)