This is the 25th day of my participation in Gwen Challenge

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 in F12 logs. 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 cross-domain HTTP request referred to in this article is initiated by XMLHttpRequest or Fetch.
  • Web fonts (CSS uses cross-domain font resources via @font-face), so Web sites can publish TrueType font resources and only allow authorized sites to make cross-site calls.
  • WebGL map.
  • Draw Images/video Images to canvas using drawImage
  • Style sheets (using CSSOM).

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 anatomy of this mechanism, you can refer to developer.mozilla.org/en-US/docs/…

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:

Add a response header

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

The filter

Add the following filters to this project:

/ solve the problem of cross-domain * * * * / public class AccessControlAllowOriginFilter implements Filter {public void doFilter (ServletRequest the 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"); The response. SetHeader (" Access - Control - Allow - Credentials ", "true"); chain.doFilter(req, response); } public void init(FilterConfig filterConfig) { } public void destroy() { } }Copy the code

Annotation way

There are a number of annotations in Spring Boot, and there are also annotations ** @crossorigin ** for cross-domain problems, 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() {... }}Copy the code

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