Use CORS+ gateway to solve cross-domain problems caused by separation of front and back ends

Insert picture description here
Nowadays mainstream development, the project requires the separation of front and back ends. This model will bring about some cross-domain problems.
There are three common solutions
: 1. Jsonp: Cross-domain through script tags
Disadvantages: Only GET requests can be initiated
2.nginx reverse proxy, you can request a variety of ways to solve a variety of cross-domain
shortcomings, complicated configuration
3. using CORS: you can request a variety of ways to solve a variety of cross-domain, custom rules, safe and reliable
used here CORS + gateway configuration steps to save us
in Gateway configuration, because all requests pass the gateway.
Write a configuration
information to configure corsconfig (CORS), and then put it in the registration config method of UrlBasedCorsConfigurationSource and
then put the source into CorsFilter() to return

The specific code is as follows
package com.TOF.canteenrobot.config;

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 GlobalCrosConfig { @Bean public CorsFilter corsFilter(){ //1. Add Cors configuration information CorsConfiguration config=new CorsConfiguration(); //1) Allowed domains. Don’t write*, otherwise the cookie cannot be used config.addAllowedOrigin("http://127.0.0.1:8020"); //2) Whether to send cookie information config.setAllowCredentials(true); //3) Allowed request method config .addAllowedMethod(“OPTIONS”); config.addAllowedMethod(“POST”); config.addAllowedMethod(“GET”); config.addAllowedMethod(“PUT”); config.addAllowedMethod(“DELETE”); config.addAllowedMethod(“PATCH ”); //4) Allowed header information config.addAllowedHeader("*"); //5) Effective duration config.setMaxAge(1800L);//Valid for half an hour



















//2. Add the mapping path, we intercept all requests
UrlBasedCorsConfigurationSource configurationSource=new UrlBasedCorsConfigurationSource();
configurationSource.registerCorsConfiguration("/**",config);
//3. Return new CorsFilter
return new CorsFilter(configurationSource);
}
}

Finally , sometimes some data types of springmvc cannot be parsed, because generally the data passed is json format, we can use entity class to receive and add @RequestBody annotation to parse json format data

Guess you like

Origin blog.csdn.net/weixin_43158695/article/details/107598312