The background,
In my spare time at work, I wrote a permission control system using AngularJS + SSM. Because of the idea of front-end and back-end separation, the inconsistent port of front-end and back-end service startup leads to cross-domain request problems. Here, write down the process for solving the problem.
Two, basic knowledge
2.1 What is homology
A URL consists of a protocol, domain name, port, and path. If the protocol, domain name, and port of two urls are the same, they are of the same origin.
2.2 What is the Same-origin Policy
The browser’s same-origin policy restricts documents or scripts from different sources from reading or setting certain properties on the current document. Its purpose is to ensure the security of user information and prevent malicious websites from stealing data.
In addition, the same-origin policy only restricts THE HTML documents of web pages, while other static resources such as javascript, CSS and images are still considered to be same-origin.
2.3 What is cross-domain
Cross-domain means that the browser cannot execute scripts from other sites. The same-origin policy states that AJAX requests can only be sent to same-origin urls, otherwise an error will be reported.
Cross-domain requests usually do not carry cookies. To enable cross-domain requests to carry cookies, you need to set the following front-end Settings:
xhr.withCredentials = trueCopy the code
This configuration requires the coordination of the back end and the access-Control-allow-credentials on the server in response, and the value must be true:
Access-Control-Allow-Credentials: trueCopy the code
With the withCredentials set to true, all cookies under this domain name are carried when communicating with the server.
Readers are advised to browse the references provided at the end of the article for further understanding of cross-domain related content, and then consider and understand the case in this paper
Third, solve the case
CORS is a W3C standard, which stands for cross-origin Resource Sharing. It allows browsers to issue XMLHttpRequest requests across source servers, overcoming the limitation that AJAX can only be used in the same source.
The author uses CORS scheme to solve the problem.
3.1 Front-end Page Settings
3.1.1 Setting Request Parameters
Add two parameter Settings to the Ajax request parameters:
xhrFields: { withCredentials: true }
crossDomain: trueCopy the code
3.1.2 Source code demo
$.ajaxsetup ({dataType: "json", cache: false, xhrFields: {withCredentials: true},// When set, requests will carry cookie crossDomain: true, complete: function(xhr) { if (xhr.responseJSON) { if (xhr.responseJSON.code == 401) { layer.msg(xhr.responseJSON.msg); setTimeout(function() { window.location.href = "login.html"; }, 1500); } } else { layer.msg(xhr.responseText); }}});Copy the code
3.2 Back-end Server Settings
3.2.1 Setting the Cross-domain Request Filter
public class SimpleCORSFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) resp; HttpServletRequest request=(HttpServletRequest)req; // Handle simple requests // Cross-domain requests do not carry cookies by default. Response. setHeader(" access-Control-allow-origin ", request.getHeader("Origin")); Responsetheader (" access-Control-allow-credentials ", "true"); response. SetHeader (" access-Control-allow-credentials ", "true"); response.setHeader(" access-Control-allow-credentials ", "true"); // Optional, set this parameter to true, corresponding to the front-end xhr.withCredentials = true; // Processing non-simple requests // Non-simple requests: The browser sends two requests. The first request (called the precheck request) determines whether the server accepts the cross-domain request, and the second actually makes the request. The browser handles both requests automatically, and precheck requests can be cached instead of having to send precheck requests every time. // Precheck requests verify that the server can handle the request before the actual request is sent. Response. setHeader(" access-Control-allow-methods ", "POST,GET,OPTIONS,DELETE"); response.setHeader(" access-Control-allow-methods ", "POST,GET,OPTIONS,DELETE"); Response. setHeader(" access-control-allow-headers ", "Origin, no-cache, x-requested-with, if-modified-since,") + "Pragma,Last-Modified,Cache-Control,Expires,Content-Type,X-E4M-With,userId,token"); response.setHeader("Access-Control-Max-Age", "0"); Response.setheader ("XDomainRequestAllowed","1"); response.setheader ("XDomainRequestAllowed","1"); response.setheader ("XDomainRequestAllowed","1"); response.setheader ("XDomainRequestAllowed","1"); chain.doFilter(req,resp); } public void init(FilterConfig filterConfig) {} public void destroy() {} }Copy the code
3.2.2 Configuring the web. XML file
<filter>
<filter-name>cors</filter-name>
<filter-class>com.light.system.web.filter.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>Copy the code
Iv. Reference materials
- www.ruanyifeng.com/blog/2016/0…
- www.ruanyifeng.com/blog/2016/0…