preface
We all know that the same origin policy makes cross-domain requests very troublesome. What are the so-called homologies that are blocking us in the first place? Homologous is a security mechanism used by browsers. Client scripts from different sources cannot read or write each other’s resources without explicit authorization. Due to the limitation of the same origin policy and the need for cross-domain services, CORS emerged.
As we all know,jsonp
You can cross domains, so why use itCORS
?
jsonp
You can only useGET
Submission of- Bad for debugging, no status code is returned when the call fails
- Security, in case if provided
jsonp
The service that it returns has a page injection vulnerabilityjavascript
The content is controlled by someone. So what’s the result? All calls to thisjsonp
Will have vulnerabilities. So there’s no way to keep the danger under one domain name… So in usejsonp
You have to make sure you use itjsonp
The service must be secure and trusted.
Start CORS
CORS is a W3C standard that stands for Cross-Origin Resource Sharing. It allows browsers to send XMLHttpRequest requests to cross-source servers, overcoming the limitation that AJAX can only be used from the same source
CORS requires browser and server support at the same time, the entire CORS communication process is automatically completed by the browser without user participation, for developers, CORS code and normal Ajax is no difference, once the browser found cross-domain request, will add some additional header information,
Is CORS so good? Are there any disadvantages?
The answer is definitely NO, all the latest browsers currently support this feature, but the evil IE can’t go below 10
Simple and non-simple requests
Browsers divide CORS requests into two categories: simple requests and non-simple requests
A simple request
All at the same time to meet the following two situations is a simple request, the reverse is not a simple request, the browser to these two kinds of request processing is not the same
- The request method is one of the following three methods
- HEAD
- GET
- POST
- HTTP header information does not exceed the following fields
- Accept
- Accept-Language
- Content-Language
- Last-Event-ID
- Content-type: only three values are allowed
application/x-www-form-urlencoded
,multipart/form-data
,text/plain
For simple requests, sending CORS requests between browsers, specifically adding an Origin field to the header, takes a look at this example
GET /cors? HTTP/1.1
Host: localhost:2333
Connection: keep-alive
Origin: http://localhost:2332
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.03578.98. Safari/537.36
Accept: */* Referer: http://localhost:2332/CORS.html Accept-Encoding: gzip, deflate, br Accept-Language: zh-CN,zh; Q = 0.9 If - None - Match: W / 1 - NWoZK3kTsExUV00Ywo1G5jlUKKs ""Copy the code
In the header above, the Origin field is used to name the source from which the request came. The server uses this value to decide whether or not to approve the request.
If Origin does not contain the access-control-allow-Origin field, the server will return a normal HTTP response, and the browser will find that the access-control-allow-Origin field is not included in the header and will throw an error. Otherwise, this field will appear (example below).
Access-Control-Allow-Origin: http://api.bob.com
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: FooBar
Content-Type: text/html; charset=utf-8
Copy the code
-
Access-control-allow-origin: this field is required to accept requests for those domains (* for all).
-
Access-control-allow-credentials This field is optional. It indicates whether cookies can be sent
-
Access-control-exposure-headers This field is optional. XHMHttpRequest object methods can only get six fields: This field specifies cache-control, content-language, Content-type, Expires, last-Modified, and Pragma.
If you want to send cookies along with them, you need to work with the server and the client
/ / the server
Access-Control-Allow-Credentials: true
/ / the client
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
If the withCredentials attribute is omitted, some browsers will still send cookies
xhr.withCredentials = false;
Copy the code
Non-simple request
A non-simple request is one of two situations that does not satisfy, such as the request is PUT, or the request header contains other fields
A CORS request that is not a simple request is a precheck request before formal communication
The browser first asks the server if the domain name of the current page can request your server, and what HTTP verbs and headers can be used. Only when the correct response is received will a formal request be made
// Front end code
var url = 'http://localhost:2333/cors';
var xhr = new XMLHttpRequest();
xhr.open('PUT', url, true);
xhr.setRequestHeader('X-Custom-Header'.'value');
xhr.send();
Copy the code
The above code uses the PUT method and sends a custom header. So it’s a non-simple request, and when the browser finds out that this is a non-simple request, it will automatically make a pre-check request to see if the server can accept the request. Here is the HTTP header for “pre-check”
OPTIONS /cors HTTP/1.1
Origin: localhost:2333
Access-Control-Request-Method: PUT // Which HTTP request method is used
Access-Control-Request-Headers: X-Custom-Header // Represents a custom field sent by the browser
Host: localhost:2332Accept-Language: zh-CN,zh; q=0.9
Connection: keep-alive
User-Agent: Mozilla/5.0.Copy the code
“Precheck” uses the request method OPTIONS, which means that the request is used to ask,
After receiving a precheck Request, the server checks the Origin, Access-control-Request-method, and Access-control-Request-headers fields, confirms that cross-source requests are allowed, and then responds.
Prechecked response header:
HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 01:15:39 GMT
Server: Apache/2.061. (Unix)
Access-Control-Allow-Origin: http://localhost:2332 // indicates that http://localhost:2332 can access data
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: X-Custom-Header
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Content-Length: 0
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Content-Type: text/plain
Copy the code
If the browser denies the precheck request and returns a normal HTTP response without any CORS header information, the browser determines that the server does not allow access and throws an error
Request after precheck
The other thing is that once the precheck request has passed, the precheck request will be made, and the request will be made in the same way as the simple request, which will have an Origin header field.
After passing the precheck, the browser sends the request
PUT /cors HTTP/1.1
Origin: http:// Api.bob.com // The Origin field is automatically attached to requests that pass precheck
Host: api.alice.com
X-Custom-Header: value
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0.Copy the code
Thank you
Thank you for reading this article. I hope it helps you. If you have any questions, please correct me.
✿ Theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus theus
Interested partners can join [front end entertainment circle exchange group] welcome everyone to exchange and discuss
Writing is not easy, “like” + “watching” + “retweet” thanks for supporting ❤
Phase to recommend
How to configure JSX
Share 15 useful Webpack plugins!!
How to write a Vue component and publish it to NPM
Sharing 12 Common Webpack Loaders
What are CommonJs and Es Modules and how they differ?
Do you know all these JavaScript Tricks for work?
【 Suggestions 】 Share some Git commands commonly used in work and how to solve special problems