This article describes the cross-domain solution I used to solve cross-domain problems caused by the front-end separation pattern in one of my projects.
First of all, understand the nature of cross-domain, that is, the same origin policy restrictions, the source is the domain name, port number, protocol, one of the different will be rejected by the browser response information, (the request can be sent, but the browser does not accept the response).
Solution:
1. jsonp
The SRC =”” attribute of jSONp is not restricted by the same origin policy, and a callback function is created dynamically. The server calls the callback function to put the data in.
Here’s a template:
$. Ajax ({type: "get", //jsonp can only use get async: false, url: "" dataType: "jsonp", jsonp: "Callback ", jsonpCallback:"message", success: function(json){}})Copy the code
If your callback function is called message, then when you return json on the back end, you should also cover it with message{}.
The disadvantage of JSONp is that it only supports GET requests because the request is sent via SRC = “”, so it is known that the URL is passed.
So what are the benefits of JSONP? Compatibility, it is supported by almost all browsers (including some older versions) and does not require XMLHttpRequest or ActiveX support.
2. cors
Also known as cross-domain access, the browser divides CORS requests into simple and non-simple requests, and since this article focuses on the details, you can check out other blogs or I’ll do a more detailed post later (along with JSONP). In SpringBoot, support is officially available. Post code directly:
Method 1: Global definition
Note the @order annotation, which will probably invalidate the configuration
@Component @Order(Ordered.HIGHEST_PRECEDENCE) public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest request = (HttpServletRequest) req; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "ACL, CANCELUPLOAD, CHECKIN, CHECKOUT, COPY, DELETE, GET, HEAD, LOCK, MKCALENDAR, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, REPORT, SEARCH, UNCHECKOUT, UNLOCK, UPDATE, VERSION-CONTROL"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, x-userId"); if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { response.setStatus(HttpServletResponse.SC_OK); } else { chain.doFilter(req, res); }}}Copy the code
Method two: local definition
@CrossOrigin(origins = "*",allowCredentials="true",allowedHeaders = "",methods = {})
Copy the code
It is convenient to add annotations directly to methods that need to cross domains. You can also use this annotation on a class.
Conclusion:
Personally, I recommend using CORS. If I have to use JSONP because of compatibility issues, I can’t help it. Then, in the mode of separation of front and back ends, user permission authentication is also a point to pay attention to. If cookie-session is used, the cross-domain background will fail to obtain the session. We can use token method to solve this problem. I plan to introduce JWT (Json Web Token) to implement user authentication later.