Simple and non-simple requests for CORS requests

reference

I. Introduction to cross-domain resource sharing CORS

The entire CORS communication process is completed automatically by the browser without user participation.

The key to CORS communication is the server. As long as the server implements the CORS interface, cross-source communication is possible.

Two kinds of requests

Browsers classify CORS requests into two categories: Simple request and not-so-simple Request.

As long as the following two conditions are met, it is a simple request.

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

  • HEAD
  • GET
  • POST

(2) HTTP headers do not exceed the following fields:

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

Any request that does not meet both conditions is a non-simple request.

Browsers treat these two requests differently.

3. Simple requests

For simple requests, the browser issues CORS requests directly. Add an Origin field to the header.

As an example, the browser automatically adds an Origin field to the header when it realizes that the cross-source AJAX request is a simple one.

4. Non-simple requests

Preview the request

Non-simple requests are requests that have special requirements on the server, such as the request method being PUT or DELETE, or the content-Type field being of Type Application/JSON.

CORS requests that are not simple requests are preceded by an HTTP query request, called a “preflight” request.

The browser asks the server if the domain name of the current web page is on the server’s license list, and what HTTP verb and header fields can be used. The browser issues a formal XMLHttpRequest request only if it receives a positive response; otherwise, an error is reported.

The request method for the “precheck” request is OPTIONS, indicating that the request is being queried. In the header information, the key field is Origin, indicating which source the request came from.

Response to precheck request

After receiving the precheck Request, the server checks the Origin, access-Control-request-method, and access-Control-request-headers fields and confirms that cross-source requests are allowed, it can respond.

Normal browser requests and responses

Once the server passes the “precheck” request, every subsequent normal BROWSER CORS request will have the same Origin header field as a simple request. The server also responds with an Access-Control-Allow-Origin header field.

V. Comparison with JSONP

CORS serves the same purpose as JSONP, but is more powerful than JSONP.

JSONP supports only GET requests, and CORS supports all types of HTTP requests. JSONP has the advantage of supporting older browsers and being able to request data from sites that do not support CORS.