This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

1, the preface

Recently, cross-origin Resource Sharing (CORS) occurred when Eureka REST interface was called in the project. I would like to share with you here to avoid more detours.

Project front-end (http://localhost:9000) by Ajax calls had REST interface (http://localhost:8761/eureka/apps), but no response, An access-Control-allow-Origin exception is found on F12. The details are as follows:

... Origin http://localhost:8761/eureka/apps. http://localhost:9000 is not allowed by the Access - Control - Allow - Origin...Copy the code

Through Google, it was found that the problem was caused by CORS crossing. There are no more than two ways to solve the problem: adding parameters to the response header and adding filters. The causes and detailed solutions of THE CORS crossing problem are described below.

2, CORS

CORS, often known as Cross problem, accurately called cross-origin Resource Sharing (CORS), is a W3C standard, is a mechanism, It uses an extra HTTP header to tell the browser to allow Web applications running on one Origin (domain) to access specified resources from different source servers. When a resource requests a resource from a different domain or port than the server on which the resource itself resides, the resource makes a cross-domain HTTP request.

http://localhost:9000 request http://localhost:8761/eureka/apps is in violation of the principle of the above, namely: Request another resource on a different port on the server, and for security reasons, the browser restricts cross-source HTTP requests. The phenomenon and exceptions mentioned at the beginning of this article occur.

For example, the XMLHttpRequest and Fetch apis follow the same origin policy, which means that Web applications using these apis can only request HTTP resources from the same domain that loaded the application, unless CORS headers are used.

The cross-domain resource sharing (CORS) mechanism allows Web application servers to control cross-domain access and secure cross-domain data transfer. Browsers support the use of CORS in API containers, such as XMLHttpRequest or Fetch, to reduce the risk associated with cross-domain HTTP requests.

When is there a cross-domain problem

  • The article mentioned byXMLHttpRequest 或 FetchInitiated across domainsHTTPThe request.
  • WebFonts (CSSThrough the@font-faceUse cross-domain font resources), so sites can publish TrueType font resources and only allow authorized sites to make cross-site calls.
  • WebGLMap.
  • usedrawImage 将 Images/videoPicture drawing tocanvasStyle sheets (useCSSOM).

How to solve the limitation of CORS

When everything in the world is done, every cause has an effect; every effect has a cause. Of course, the restrictions of CORS, the official solution is also provided.

The CORS standard adds a new set of HTTP header fields (Access-Control-Allow-Origin) that Allow the server to declare which sources have Access to which resources through the browser. In addition, the specification requires that HTTP request methods (especially HTTP requests other than GET, or POST requests paired with certain MIME types) that may have adverse effects on server data, The browser must first issue a preflight request using the OPTIONS method to know whether the server will allow the cross-domain request. The actual HTTP request is made only after the server confirms that it is allowed. In the return of the precheck request, the server side can also inform the client whether it needs to carry identity credentials (including Cookies and HTTP authentication related data).

CORS request failures generate errors, but for security reasons, there is no way to know exactly what went wrong at the JavaScript code level. You can only look at your browser’s console to see exactly what went wrong.

If you are interested in understanding the mechanism of anatomy can refer to: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

3. Solutions

After reviewing a lot of resources and learning about the CORS mechanism, the solution essentially revolves around the Access-Control-Allow-Origin header.

The solutions are as follows:

Method 1: Add the response header

Add the response header “access-Control-allow-origin: *” to the requested resource

Method 2: Filters

Add the following filters to this project:

/** * Resolve cross-domain issues */
public class AccessControlAllowOriginFilter implements Filter {
 
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin"."*");
        response.setHeader("Access-Control-Allow-Methods"."POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Credentials"."true"); chain.doFilter(req, response); }public void init(FilterConfig filterConfig) {}public void destroy(a) {}}Copy the code

Method 3: Annotation method

Spring Boot has a large number of annotations. For cross-domain problems, there is also a corresponding annotation @crossorigin, which can be used as follows:

import java.util.HashMap;
 
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
/ * * *@author xcbeyond
 */
@RestController
@RequestMapping(value = "/api", method = RequestMethod.POST)
public class DemoController {
        
    @CrossOrigin(origins = "*")
    @RequestMapping(value = "/get")
    public String get(a) {... }}Copy the code

Personal comparison recommends using one of the above three ways, other ways please their baidu, Google bar