Simple and complex cross-domain request ajax request

Web site often used when developing cross-domain resource sharing (referred cors, referred to later use) to solve cross-domain problems, but when using cors of, http request will be divided into two categories, simple and complex requests and requests, and these two the main difference is whether the kind of request will trigger cors preflight request.

First we need to understand the principles of cors (cited MDN):

Cross-Origin Resource Sharing standard adds a set of HTTP header fields, which allows the server to declare the source station through a browser which has permission to access the resource. Additionally, regulatory requirements, may produce adverse effects on those data to the server HTTP request method (in particular, other than the HTTP request GET, or with a certain MIME type POST request), the browser must first use the OPTIONS method to initiate a request for pre-screening ( preflight request), so that the server know whether to allow the cross-domain request. After the server acknowledges permission before initiating the actual HTTP request. In return preflight request, the server can inform the client, whether you need to carry identity documents (including Cookies and HTTP authentication-related data)

From the above text we get the following information:

1, the cross-domain resource sharing a set of new standard HTTP header field, control the browser by the server to which resources have access to these fields.

2, a request for security reasons divided into two categories, options requests are not sent in advance, a number of options will send a request in advance.

3, other than GET HTTP request, or with certain MIME type of the POST request will trigger options request.

4, after completion will allow the server to verify OPTIONS http requests of the world.

Http request does not trigger pre-screening is a simple request, the idea can trigger a preflight request http request is complicated.

What a simple request that it be? The following is a quote from the official MDN:

1, use one of the following methods:

GET、

POST、

HEAD。

2, shall not be provided to other people other than the header fields set. The collection is:

Accept

Accept-Language

Content-Language

Content-Type

3. Content-Type value is limited to one of the following three:

text/plain

multipart/form-data

application/x-www-form-urlencoded

4, subject to any XMLHttpRequestUpload request did not register any event listeners; XMLHttpRequestUpload object can be accessed using XMLHttpRequest.upload property

5, the object request is not used ReadableStream

So what is a complex request it, in addition to simple requests are complicated request.

Simple request sent from the point of view and the code Common XHR not much difference, but among the HTTP header field always contains a request for information (Origin) a. This field contains the protocol name, address, and an optional port. But this one is actually sent on his behalf by the browser, not the developer's code can be touched.

Simple request response header portion and explained as follows:

Access-Control-Allow-Origin (mandatory) - can not be omitted, otherwise, failure processing according to the request. The visible range of the control data, if you want data is visible to anyone, you can fill out the "*." Access-Control-Allow-Credentials (optional) - this marks the request which contains information about cookies, there is only one possible values: true (must be lowercase). If you do not include cookies, please omit the item, rather than fill out false. This is a property with withCredentials among XmlHttpRequest2 object should be consistent, that is true withCredentials this also is true; when withCredentials is false, the omission does not write. Otherwise the request failed. Access-Control-Expose-Headers (optional) - The additional information that determines an object among the getResponseHeader XmlHttpRequest2 () method can be obtained. Typically, getResponseHeader () method can only obtain the following information: Cache-Control Content-Language Content-Type Expires Last-Modified Pragma When you need to access additional information, we need to fill in this one of them and comma separated

If only a simple request, even without CORS is no big deal, but the complexity of the request CORS CORS will make it even more useful. Briefly, a simple request does not satisfy the requirements of any requested, they belong to complex requests. For example, you need to send PUT, DELETE and other HTTP verbs, or send Content-Type: application / json content.

On complex requests and seemingly simple request similar use, but in fact more than one browser sends a request. Wherein the first transmission is a "pre-request", this time as a server, but also need to return to "pre-response" as a response. Pre request is actually a kind of server requests permission only if the pre-request returns successfully, the actual request was started.

OPTIONS request is sent to the pre-form, which contains the same domain, and further comprising two unique content CORS

Access-Control-Request-Method - The content type is actually requested, a request may be a simple GET, POST and the like, may be PUT, DELETE and the like. Access-Control-Request-Headers - this is a comma-separated list, which is used in the request header complex.

Obviously, this is actually a pre-request permission to send a request to return the contents of the pre-response among the server should reply with these two, in order to allow the browser to determine whether the request can be completed successfully after the actual request is.

Complex request response header portion and explained as follows:

Access-Control-Allow-Origin (mandatory) - and as a simple request must include a domain. Access-Control-Allow-Methods (mandatory) - This is a request for which the pre-Access-Control-Request-Method response, this response will be a comma-separated list. Although the client may only request a certain way, but the server can still return all allowed methods, so that clients will cache it. Access-Control-Allow-Headers (when the request contains pre-Access-Control-Request-Headers must contain) - This is a reply to the request which pre-Access-Control-Request-Headers, the same as above, and comma-separated list of You can return all the support of the head. Here are encountered in actual use, all supported temporary head may not be completely written out, but do not want to do too much at this level of judgment, it does not matter, in fact you can take to Access-Control- through the header request directly Request-Headers, directly to the set value corresponding to the Access-Control-Allow-Headers can. Access-Control-Allow-Credentials (optional) - and the same effect among the simple request Access-Control-Max-Age (optional) - time in seconds cache units. Pre requested to send lunch is not free, it should be allowed to cache as possible.

This theoretical talk, let's look at the practice, first start two services, a port 3000, a static resource server for the request interface, another interface server port 5000, as shown:

 

Backend interface server code is as follows:

const  express = require("express");

const app = express();

const bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({extended:false}));

app.use(bodyParser.json());

// achieve CORS

app.use(function(req, res, next) {

    res.header("Access-Control-Allow-Origin", "*");

    res.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST,PUT,DELETE');

    res.header("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept,Authorization");

    res.header("cache-control", "no-cache");

    res.header("content-type", "application/json; charset=utf-8");

    res.header("ETag", '');

    next();

});

app.post("/p",(req,res)=>{

    res.send(req.body)

})

 

app.listen(5000,()=>{

    console.log("5000")

})

The front end of the requested resource script code is as follows:

axios.post("http://localhost:5000/p",{name:"zs",age:"18"}).then((data)=>{

    console.log(data.data);

})

We axios this library http request to send a post request, axios default will send a post request data into json format, and the default settings will request header: Content-Type: application / json, it is clear that this is a complex request, such then the request will trigger options.

We were to start two services, and open a browser to access the page, load request interface script, observing network as shown:

 

We see the code name only sent an asynchronous request Why do it twice? Detailed shots are as follows:

 

 

We see indeed sent two requests for the first time for the OPTIONS POST, and we did not handle the response code to handle the OPTIONS request, so the above server code is unreasonable, considering, and will actually http OPTIONS request request affect poor students, so we are unified to return to the OPTIONS request 204, the server is responsible for supporting CORS middleware correction code is as follows:

app.use(function(req, res, next) {

    res.header("Access-Control-Allow-Origin", "*");

    res.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST,PUT,DELETE');

    res.header("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept,Authorization");

    res.header("cache-control", "no-cache");

    res.header("content-type", "application/json; charset=utf-8");

    res.header("ETag", '');

    // the end of the first header information set, the end of the program execution down, return

    if(req.method.toLocaleLowerCase() === 'options'){

        res.status(204);

        return res.json ({}); // null data directly back to the end of the request

    }else{

        next();

    }

});

in conclusion:

1. a simple request:

Meet at the request of two conditions.

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

  • HEAD
  • GET
  • POST

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

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

2. complex requests:

Non-simple request is complex requests.

Request is a non-simple that there is a request to the server special requirements, such as the DELETE or PUT request method is, or the type of field Content-Type is application / json.

Non-simple request CORS request, before the official communication, increase an HTTP query request, called "preflight" request (preflight).

OPTIONS preflight request as a request for information to the requesting authority server.

After the preflight request is successful response is issued until the real request, carry real data.

axios default request is application / json, so do not need to add head (no need to config Canada headers), so always request will be issued options, and see the time is not added to the configuration of unnecessary headers configuration items .
In addition, if you really need preflight background also needs to be set to allow the request options.

 

Guess you like

Origin www.cnblogs.com/ranyonsue/p/11770769.html