What is cross-domain?
General format of Url:
Protocol + Domain name (subdomain name + primary domain name) + port number + resource address
Example:
https://www.hechangqun.cn:8080/say/Hello is a
HTTPS + WWW + hechangQun.cn + 8080 + say/Hello.
If one of the four components of the protocol, subdomain name, main domain name, or port number is different, it can be considered as a different domain. Different domains access each other’s resources, which is called cross-domain.
Cross-domain test
Take Chrome as an example:
-
Open any web site, such as blog.csdn.net
-
Press F12 to open the “Developer Tools”, in the “Console” can directly enter js code test;
var token= “LtSFVqKxvpS1nPARxS2lpUs2Q2IpGstidMrS8zMhNV3rT7RKnhLN6d2FFirkVEzVIeexgEHgI/PtnynGqjZlyGkJa4+zYIXxtDMoK/N+AB6wtsskYXereH3 AR8kWErwIRvx+UOFveH3dgmdw1347SYjbL/ilGKX5xkoZCbfb1f0=,LZkg22zbNsUoHAgAUapeBn541X5OHUK7rLVNHsHWDM/BA4DCIP1f/3Bnu4GAElQU6c ds/0fg9Li5cSPHe8pyhr1Ii/TNcUYxqHMf9bHyD6ugwOFTfvlmtp6RDopVrpG24RSjJbWy2kUOOjjk5uv6FUTmbrSTVoBEzAXYKZMM2m4=,R4QeD2psvrTr8 tkBTjnnfUBw+YR4di+GToGjWYeR7qZk9hldUVLlZUsEEPWjtBpz+UURVmplIn5WM9Ge29ft5aS4oKDdPlIH8kWNIs9Y3r9TgH3MnSUTGrgayaNniY9Ji5wNZ iZ9cE2CFzlxoyuZxOcSVfOxUw70ty0ukLVM/78=”;
var xhr = new XMLHttpRequest(); XHR. Open (‘ GET ‘and’ http://127.0.0.1:8080/demo/sayHello ‘); xhr.setRequestHeader(“x-access-token”,token); xhr.send(null); xhr.onload = function(e) { var xhr = e.target; console.log(xhr.responseText); }
-
After typing, press enter directly to return the result:
Access to the XMLHttpRequest at ‘http://127.0.0.1:8080/demo/sayHello’ from origin ‘blog.csdn.net’ has had been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. 123
The result indicates that the request failed under the domain name https://blog.csdn.net!
The solution
Set the Cors
CORS is called Cross Origin Resource Sharing (Cross-domain Resource Sharing). Each page needs to return an HTTP header named Access-Control-Allow-Origin to Allow outdomain sites to Access. You can only expose limited resources and limited outdomain site access.Copy the code
If a request needs to Allow cross-domain Access, you need to set access-Control-allow-Origin in the HTTP header to determine which sites need to Allow Access. If you assume that you want to allow cross-domain requests for the site www.dustyblog.c, you can set:
Access-Control-Allow-Origin:https://www.dustyblog.cn.
Plan 1: Use @crossorigin annotations
Use the @crossorigin annotation on Controller
All interfaces under this class can be accessed across domains
@requestMapping ("/demo2") @restController // @crossorigin // All domain names can access all interfaces in this class @crossorigin ("https://blog.csdn.net") // Only the specified domain name can access all interfaces in this class. Public Class CorsTest2Controller {@getMapping ("/sayHello") public String sayHello() {return "hello" world --- 2"; }}Copy the code
Scheme 2: CORS global configuration – WebMvcConfigurer implementation
-
New cross-domain configuration class: corsconfig.java:
/ * *
- Cross-domain configuration
*/ @Configuration public class CorsConfig implements WebMvcConfigurer {
@Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**"). allowedOrigins("https://www.dustyblog.cn"). // Allow cross-domain domain names, AllowedMethods ("*") are allowed for any domain name. // allowedHeaders("*") are allowed for any method (post, GET, etc.). // allowCredentials(true) for any request header. ExposedHeaders (HttpHeaders.set_cookie).maxage (3600L); //maxAge(3600) indicates that within 3600 seconds, no more pre-validation requests need to be sent and the result can be cached}}; }Copy the code
}
Scheme three: interceptor implementation
Cross domain issues are addressed by implementing the Fiter interface to add some headers to the request
@Component
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Credentials", "true");
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
response.getWriter().println("ok");
return;
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
Copy the code