CORS

Cross-origin Resource Sharing (CORS) defines how browsers and servers communicate across sources. The idea behind CORS is to use custom HTTP headers.

When making a cross-domain request, browsers divide the request into two types, simple request and non-simple request, and the two types of request are handled differently.

A simple request

Simple requests are made to be compatible with forms because forms can be made across domains. A simple request is one that meets the following conditions.

  • The request method isGET,POST,HEADmethods
  • Request header forAccept,Accept-Language,Content-Type

Content-type can only be Application/X-ww-formurlencoded, multipart/form-data, text/plain, for example, Application /json is a non-simple request.

When a browser makes a simple request, it adds an Origin field in the HTTP header to indicate the source of the request (protocol + domain + port). The server determines whether the source is within the licensed range based on the source.

If the source is not within the license scope, the server responds normally. However, if the browser does not find the access-Control-Allow-Origin header in the response, it will throw an error that will be caught by XHR’s error event handler.

If the source is within the permitted range, access-Control-allow-Origin is added to the request source or * in the response header,

Other response headers:

  • Access-Control-Allow-HeadersRepresents the field that can appear in the request header.
  • Access-Control-Allow-MethodsRepresents a method that can be requested
  • Access-Control-Allow-CredentialsIndicates whether cookies can be carried
If a request needs to carry cookies, if it is made through an XMLHTTPRequest object, then the client should set xhr.withCredentials to true, which is generally true by default, and can be set to false to disable. The access-Control-allow-credentials parameter must be set to true on the server that does not send cookiesCopy the code

Non-simple request

Except for simple requests, which are non-simple requests. Before a non-simple request, the browser sends a precheck request and determines whether to send the request based on the response.

Preview the request

The precheck request is an option request that adds three headers

  • OriginIndicates that the source
  • Access-Control-Request-MethodRepresents the method of the request
  • Access-Control-Request-HeadersRepresents the header to be used in the request

The server looks at the method of the request and whether the other headers are within its own limits. If so, the corresponding field is returned.

If the server does not support the cross-domain request, the normal HTTP response is returned, that is, withoutAccess-Control-Allow-**Similar to the field, the browser will automatically intercept the error.

  • Access-Control-Allow-Max-AgeIt looks like a cachePrecheck the request response“, in seconds, but IT didn’t seem to work when I tried.

If the precheck request passes, the request is normally sent and an Origin field is added. If the pre-check request doesn’t pass, there’s no follow-up, nothing will be sent. The response must always carry the access-Control-allow-XX response header, otherwise the precheck request will not work. Subsequent requests are also blocked by the browser


JSONP

JSONP makes use of

function JSONP(src, callback, id) { let script = document.createElement("script"); script.src = src + "? callback=" + callback + "&id=" + id; document.body.append(script); } function getPerson(res) { console.log(res); } JSONP("http://localhost:3000", "getPerson", 1);Copy the code

Server code

let person = [ { id: 1, name: "zs", age: 22 }, { id: 2, name: "ls", age: 20 }, ]; server.get("/", (req, res) => { let cb = req.query.callback let id = req.query.id || 0 let someone = person.find(ele => ele.id == id) || "No such person" res. Send (` ${cb} (${JSON. Stringify (someone)}) `); });Copy the code

The server returns a string, the front end requests it back as JS code to execute the predefined method, and the server puts the values the front end needs in the parameters of the method

Content-Type

Application/X-www-formurlencoded and multipart/form-data are form-sending coded, what’s the difference

Application/X-www-formurlencoded send key-value pairs in form name=zs&age=22.

Multipart /form-data is segmented by boundary