One, foreword

In everyday development, you might occasionally see two requests to the same interface, and the first request is of type Options. We examined the code and found that the request was not initiated by us developers, it was browser behavior. So why the request?

2, the function of options request

Options requests actually occur during cross-domain resource access, which uses a mechanism to check whether the server will allow the actual request to be sent. This mechanism uses the browser to issue a “pre-check” request to the 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.

When will the options request occur

Options requests do not occur in all HTTP cross-domain requests. Requests that meet the following criteria are called simple requests and do not trigger options:

  • Use one of the following methods: GET HEAD POST
  • Except for header fields that are automatically set by the User Agent (for example, Connection, user-agent) and other headers that are defined in the Fetch specification to disable header names, fields that are allowed to be set artificially are the set of CORS safe header fields defined by the Fetch specification. The set is: Accept accept-language content-language content-type DPR Downlink Save-Data viewport-width Width Content-type values are limited to one of the following: Text /plain Multipart /form-data application/ X-www-form-urlencoded
  • None of the XMLHttpRequestUpload objects in the request have any event listeners registered; The XMLHttpRequestUpload object can be accessed using the xmlHttprequest.upload attribute.
  • No ReadableStream object is used in the request.

Options requests that do not meet the above conditions will occur across domains because the browser is not sure whether these requests will have unpredictable effects on the server. At the same time, when issuing the options request, the server needs to return the corresponding header to carry out the real request.

The common scenarios where options requests occur are as follows:

  • Use get/ POST /head request Methods Put, Delete, Trace, Connect The server needs to return access-Control-allow-methods: POST, get, OPTIONS
  • SetRequestHeader (‘ x-pingother ‘, ‘pingpong’) using custom HTTP headers or headers that are not in the above range; The server must return access-Control-allow-headers: x-pingother, content-type
  • SetRequestHeader (‘ content-type ‘, ‘application/ XML ‘); The server needs to return access-Control-allow-headers: content-type
  • WithCredentials = true; The server needs to return access-Control-allow-credentials: true

So that’s some explanation of options requests

reference

Cross-source resource sharing (CORS) CORS -safelisted-request-header