When AJAX cross-domain POST sends json, an OPTIONS pre-request will be sent first

We will find that there will be an options request before many post, put, delete and other requests.

The fundamental reason is that the W3C specification requires it! In cross-domain requests, it is divided into simple requests (get and partial post, content-type is one of application/x-www-form-urlencoded, multipart/form-data, text/plain) and complex requests. Before a complex request is issued, an options request occurs.

What is an options request? It is a probing request by which a client can decide what necessary action to take for a specific resource, or learn about the performance of the server, before making a request for a specific resource.

The options request in ajax is also a kind of early detection. When an ajax cross-domain request is made, if the request is json, it is a complex request. Therefore, an options request needs to be issued in advance to check whether the request is reliable and safe. If the response obtained by options is of a rejection nature, such as http status such as 404\403\500, the sending of post, put and other requests will be stopped.

Although it was suggested in the following references that the options request can be cancelled, it was found to be impossible after the actual measurement. After the jquery package is encapsulated, it cannot be easily cancelled. Therefore, it is impossible to cancel the options request by the javascript client. Only the server can make a correct response to the options request, so as to ensure that after the options request, post, put and other requests can be sent. However, we cannot allow all options requests, but should be conditional, so it is best to use a special mechanism to verify whether the options request data sent by the client meets the conditions of the server, if not, return 403 , the client will cancel the original post plan.

 

 

For cross-domain post requests in the foreground, due to the existence of the CORS (cross origin resource share) specification, the browser will first send an options sniff, and the header will bring origin to determine whether there is a cross-domain request permission, and the server responds to the value of access control allow origin , for the browser to match the origin, and if it matches, the post request is officially sent.

If you have server program permissions, set, for example, in jsp, set header access control allow origin equal to *, you can get the purpose of cross-domain access.

 

Excerpted from the blog "The Sunshine Years of Youth"

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324478755&siteId=291194637