Cors solves cross domain problems


Problem: axios requests. There are two requests, one of which is Request Method: OPTIONS

Reason: cross domain reason

Cross domain problem

What is cross domain

Cross domain refers to cross domain access. The following situations belong to cross domain:

Cross domain reason descriptionExample
Different domain and
The domain name is the same, but the port is and
Different secondary domain and

If the domain name and port are the same, but the request path is different, it does not belong to cross domain, such as:

And my problem is because from Go visit , this belongs to the second level domain name, which is different and cross domain

Why cross domain

Cross domain does not necessarily have cross domain problems.

Because the cross domain problem is a limitation of the browser on ajax: the ajax request initiated by a page can only be the path of the same domain name as the current page, which can effectively prevent cross site attacks.

Solutions to cross domain problems

At present, there are three common cross domain solutions:

  • Jsonp

    The earliest solution is based on the principle that script tags can be implemented across domains.


    • Service support required
    • Only GET requests can be initiated
  • nginx reverse proxy

    The idea is: use nginx reverse proxy to change cross domain to non cross domain, and support various request modes

    Disadvantages: additional configuration is required in nginx, and the semantics is not clear

  • CORS

    Standardized cross domain request solution, safe and reliable.


    • Control whether cross domain is allowed on the server, and you can customize the rules
    • Support various request modes


    • Additional requests will be generated

We will adopt the cross domain solution of cors.

cors solves cross domain

What is cors

CORS is a W3C standard, whose full name is "cross origin resource sharing".

It allows browsers to send messages to cross source servers XMLHttpRequest Request, which overcomes the problem that AJAX can only Homology Restrictions on use.

CORS requires both browser and server support. At present, all browsers support this function, and IE browser cannot be lower than IE10.

  • Browser side:

    At present, all browsers support this function (not below IE10). The whole CORS communication process is completed automatically by the browser without user participation.

  • Server:

    CORS communication is no different from AJAX, so you don't need to change the previous business logic. However, the browser will carry some header information in the request. We need to judge whether to run it across domains, and then add some information to the response header. This is usually done through filters.


The browser will divide ajax requests into two categories, and their processing schemes are slightly different: simple requests and special requests.

Simple request

As long as the following two conditions are met at the same time, it is a simple request

(1) The request method is one of the following three methods:

  • HEAD
  • GET
  • POST

(2) The header information of HTTP does not exceed the following fields:

  • Accept
  • Accept-Language
  • Content-Language
  • Last-Event-ID
  • Content type: limited to three values: application/x-www-form-urlencoded, multipart / form data, and text/plain

When the browser finds that the initiated ajax request is a simple request, it will carry a field in the request header: Origin

Origin will indicate which domain the current request belongs to (protocol + domain name + port). The service will decide whether to allow it to cross domains based on this value.

If the server allows cross domain, the following information needs to be carried in the returned response header:

Access-Control-Allow-Credentials: true
Content-Type: text/html; charset=utf-8
  • Access control allow origin: an acceptable domain, which is a specific domain name or *, representing any domain name
  • Access control allow credentials: whether cookies are allowed to be carried. By default, cors will not carry cookies unless this value is true

be careful:

If a cross domain request wants to operate cookie s, three conditions must be met:

  • The response header of the service needs to carry access control allow credentials and be true.
  • The browser needs to specify withCredentials as true to initiate ajax
  • The access control allow origin in the response header must not be *, but must be a specific domain name
Special request

If a simple request does not meet the conditions, it will be judged as a special request by the browser. For example, the request method is PUT.

Pre inspection request

Special requests will add an HTTP query request before formal communication, which is called "preflight".

The browser first asks the server whether the domain name of the current web page is in the server's license list, and what HTTP verbs and header information fields can be used. Only when you get a positive reply will the browser send a formal XMLHttpRequest request, otherwise an error will be reported.

A template for a "pre check" request:

OPTIONS /cors HTTP/1.1
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: X-Custom-Header
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0...

Compared with simple requests, there are two more headers besides Origin:

  • Access control request method: the next request method, such as PUT
  • Access control request headers: header information for additional use

Response to pre inspection request

The service receives a pre check request. If the license is cross domain, it will send a response:

HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 01:15:39 GMT
Server: Apache/2.0.61 (Unix)
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: X-Custom-Header
Access-Control-Max-Age: 1728000
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Content-Length: 0
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Content-Type: text/plain

In addition to access control allow origin and access control allow credentials, there are three additional headers:

  • Access control allow methods: allowed access methods
  • Access control allow headers: allowed headers
  • Access control Max age: the valid duration of this license is in seconds. ajax requests before expiration do not need to be pre checked again

If the browser receives the above response, it is considered that it can cross domain, and the subsequent processing is the same as that of a simple request.


Although the principle is complex, as mentioned earlier:

  • Browser side browsing is automatically completed by the browser, we don't need to worry
  • The server can be implemented uniformly through interceptors, and there is no need to write cross domain decisions every time.

In fact, spring MVC has helped us write the cross domain filter of CORS: CorsFilter, which has implemented the decision logic just mentioned. We can just use it directly.

Write a configuration class in ly API gateway and register CorsFilter:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

public class GlobalCorsConfig {
    public CorsFilter corsFilter() {
        //1. Add CORS configuration information
        CorsConfiguration config = new CorsConfiguration();
        //1) Do not write *, otherwise the cookie will not be used
        //2) Send Cookie information
        //3) Allowed request mode
        // 4) Allowed header information

        //2. Add a mapping path and we will intercept all requests
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);

        //3. Return to the new CorsFilter
        return new CorsFilter(configSource);

Tags: node.js Nginx Spring Boot Ajax

Posted on Thu, 23 Sep 2021 03:10:25 -0400 by Mattyspatty