We have encountered front-end cross-domain problems in the previous project, so we hereby record them for future reference.

There are many ways to solve the front-end cross-domain problem, one of which is to configure the cross-domain code in the target service of the page request. Because our project is separated from the front and back ends, and the back end is unified to carry out request forwarding through the routing gateway, I only need to configure the cross-domain code in the routing gateway service, the code is as follows:

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableZuulProxy
public class ZuulApplication {

	public static void main(String[] args) {
		SpringApplication.run(ZuulApplication.class, args);
	}

	/** * attention: GET, HEAD, and POST requests But the "Content-type" of POST requests can only be Application/X-www-form-urlencoded, multipart/form-data or text/plain * otherwise, it is non-simple cross-domain, which has a pre-check mechanism. To put it bluntly, there will be two requests, one for OPTIONS and one for real */
	@Bean
	public CorsFilter corsFilter(a) {
		final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		final CorsConfiguration config = new CorsConfiguration();
		config.setAllowCredentials(true); // Allow cookies to cross domains
		config.addAllowedOrigin("*");// # allow request urIs to be submitted to the server. * indicates that all requests are allowed. In SpringMVC, if set to *, Origin is automatically converted to the current request header
		config.addAllowedHeader("*");// # allow access to the header,* represents all
		config.setMaxAge(18000L);// Precheck request cache time (seconds), i.e., the same cross-domain request will not be prechecked again during this time
		config.addAllowedMethod("OPTIONS");// Methods that allow requests to be submitted, * means all requests are allowed
		config.addAllowedMethod("HEAD");
		config.addAllowedMethod("GET");// Request methods that allow Get
		config.addAllowedMethod("PUT");
		config.addAllowedMethod("POST");
		config.addAllowedMethod("DELETE");
		config.addAllowedMethod("PATCH");
		source.registerCorsConfiguration("/ * *", config);
		return newCorsFilter(source); }}Copy the code

The key code above to resolve the cross-domain problem is the corsFilter method, so that we can request the gateway service from the front end again and the cross-domain problem will not occur again.

Nginx port forwarding is recommended to solve cross-domain problems. The portal is as follows:

Nginx reverse proxy solves cross-domain problems