Cross-domain problems: three solutions to cross-domain solutions
When the front-end page and the background run on different servers, the problem of cross-domain will inevitably occur. This article briefly introduces three solutions to solve the cross-domain. Some code screenshots are as follows, for reference only:
Method 1: Use jsonp of ajax
Disadvantages of using this method for front-end code
server code
: The request method can only be get request
method 2: Use jQuery's jsonp plugin
Plugin download URL: https://github.com/jaubourg/jquery-jsonp
front-end code
The characteristics of the server code
using this method: Compared with method 1, the request method is not limited to get requests, but also post requests, but the data obtained from the server is still in jsonp format
. Method 3: Use cors
front-end code
Server code
The characteristics of using this method: Compared with the first two methods, the front-end code is the same as before the cross-domain processing, that is, the normal ajax request, but the server code adds a piece of code to solve the cross-domain solution
// Setting: Access-Control -Allow-Origin header, dealing with Session issues
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true" );
response.setHeader("P3P", "CP=CAO PSA OUR");
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod() )) {
response.addHeader("Access-Control-Allow-Methods", "POST,GET,TRACE,OPTIONS");
response.addHeader("Access-Control-Allow-Headers", "Content-Type,Origin,Accept ");
response.addHeader("Access-Control-Max-Age", "120");
}
Advanced use of cors: Configure interceptors in springmvc
Create a cross-domain interceptor to implement the HandlerInterceptor interface and implement its methods, set header information before request processing, and release
the interceptor in the configuration file of springmvc, pay attention to intercepting all document