Phenomenon of the problem

H5 and Web are in different domain names. Because web Nginx does not configure a whitelist to allow H5 to access web resources, a cross-domain problem occurs when H5 accesses web resourcesCopy the code

Introduction to cross-domain principles

The cross-domain problem is caused by the same origin policy of the browser. To improve website security, the browser allows access to ajax requests only when the current page address is the same as the protocol, domain name, and port number of the requested address. Otherwise, the request will be blockedCopy the code

handling

  • Nginx reverse proxy
  • Cors (Cross-domain Resource Sharing)

Nginx reverse proxy – corresponds to the nginx cross-domain configuration shown in the figure above

Nginx configures iframe same-origin access

Add_header x-frame-options allows SAMEORIGIN to be the same as the current nginx Web service.Copy the code

Nginx allows specified domain names to be accessed

Map $http_origin $cors_list{default http://xxx-te.test.xxxfintech.com; "~^http://xxx-te.test.xxxfintech.com" http://xxx-te.test.xxxfintech.com; "~^http://xxx-h5te.test.xxxfintech.com" http://xxx-h5te.test.xxxfintech.com; } ## server add_header 'access-control-allow-origin' '$cors_list';Copy the code

Cors (Cross-domain resource Sharing)- corresponds to the gateway cross-domain configuration shown in the figure above

Add cross-domain configuration classes in spring-Cloud-Gateway

@Configuration public class CorsAutoConfiguration { @Autowired private GlobalCorsProperties globalCorsProperties; @Bean public CorsWebFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser()); globalCorsProperties.getCorsConfigurations().forEach((path,corsConfiguration)->source.registerCorsConfiguration(path, corsConfiguration)); return new CorsWebFilter(source); }}Copy the code

Configure in NACOS

spring: cloud: gateway: globalcors: cors-configurations: '[/**]': allow-credentials: true allowed-origins: # Configure the allowed domain name - "http://xxxx" - "https://xxxx" allowed-headers: "*" allowed-methods: "*" max-age: 3600Copy the code