Cross-source resource sharing (CORS) (or more popularly known as cross-domain resource sharing) is an HTTP header based mechanism that allows a server to identify other origins (domains, protocols and ports) besides its own, so that browsers can access and load those resources. Cross-source resource sharing also checks whether the server will allow a real request to be sent by issuing a “pre-check” request via the browser to a server-hosted cross-source resource. In precheck, the browser sends headers that are identified with HTTP methods and those that will be used in real requests.

By default, the same-origin security policy prevents cross-domain access to resources. But CORS gives Web servers the option to allow cross-domain requests to access their resources.

CORS head

  • Access-Control-Allow-Origin

Indicates to which domains the requested resource can be shared.

  • Access-Control-Allow-Credentials

Indicates whether to respond to a request when its credentials are marked true.

  • Access-Control-Allow-Headers

Used in response to a pre-request to indicate which HTTP headers can be used in the actual request.

  • Access-Control-Allow-Methods

Specifies which HTTP methods in the response to a pre-request allow access to the requested resource.

  • Access-Control-Expose-Headers

Indicates which HTTP header names can be listed in the response.

  • Access-Control-Max-Age

Indicates how long the results of a pre-request can be cached.

  • Access-Control-Request-Headers

Used to make a pre-request that tells the server which HTTP headers will be used for a formal request.

  • Access-Control-Request-Method

Use to make a pre-request that tells the server which HTTP request method will be used for the formal request.

  • Origin

Indicates the domain from which the request for the resource originated.

Resolve ajax requests across domains

1. Add Response configuration on the server.

Access-control-allow-origin: access-Control-content-headers: * // Access-Control-allow-origin: Access-control-allow-methods: * / access-control-allow-credentials: True // Responds to a request when its credentials are marked true. Respond to a request with a CookieCopy the code

2. Configure the Web clientwithCredentialsattribute

CORS requests do not send cookies and HTTP authentication information by default. If you want to send cookies to the server, specify the access-Control-allow-credentials field and set the withCredentials attribute to true in the AJAX request.

Var XHR = new XMLHttpRequest(); xhr.withCredentials = true; // Jquery Ajax configuration $. Ajax ({type:"POST", xhrFields: {withCredentials: true // When sending Ajax, the Request header contains Cookie information. }, url: "", data:{"id": "5fae478d92beb55653221b20"}, success:function(res){ console.log(res) } })Copy the code

The related documents

  • Developer.mozilla.org/zh-CN/docs/…
  • Developer.mozilla.org/zh-CN/docs/…