The ajax request of the browser same-origin policy cannot be sent

The same-origin policy is the cornerstone of browser security

Homology means three identical
write picture description here

Restricted range

(1) Cookie、LocalStorage 和 IndexDB 无法读取。

(2) DOM 无法获得。

(3) AJAX 请求不能发送。

The following focuses on explaining that AJAX requests cannot be sent:
the same-origin policy stipulates that AJAX requests can only be sent to the same-origin URL, otherwise an error will be reported.
There are 4 ways to circumvent this limitation:

1.JSONP
2.WebSocket
3.CORS
4.架设服务器代理

1. The basic idea of ​​JSONP
is that the web page requests JSON data from the server by adding an <script>element, which is not restricted by the same-origin policy (only 3 types are limited, as mentioned above); a key point is to allow users to pass a callback parameter Give it to the server, and when the server returns the data, it will wrap the JSON data with the callback parameter as the function name

function addScriptTag(src) {
  var script = document.createElement('script');
  script.setAttribute("type","text/javascript");
  script.src = src;
  document.body.appendChild(script);
}

window.onload = function () {
  addScriptTag('http://example.com/ip?callback=foo');
}

function foo(data) {
  console.log('Your public IP address is: ' + data.ip);
};

Limitations and security
1.JSONP is only applicable to http get requests. Only using GET request means a lot of restrictions. For example, the default limit of nginx server is 4K or 8K, which is related to the hardware configuration of the server. Generally, it is the size of one page of memory. At present, most of them are 4K, that is, 4096 words. Section
2. JSONP lacks an error handling mechanism. If the script is injected successfully, the callback function will be called, but after the injection fails, there is no prompt.
3. In terms of security, cross-site request forgery (CSRF) attack is possible with the help of JSONP. When a malicious website uses the visitor's browser to send a request to the server and make data changes, it is called a CSRF attack. Since the request will carry cookie information, the server will think that the user wants to submit a form or send a request, and obtain some private data of the user

2.WebSocket

WebSocket is a communication protocol that uses ws:// (non-encrypted) and wss:// (encrypted) as protocol prefixes. The protocol does not enforce a same-origin policy, and cross-origin communication is possible through it as long as the server supports it.

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com

In the above code, one field is Origin, which indicates the origin of the request, that is, which domain name it is sent from.

It is precisely because of the Origin field that WebSocket does not implement the same-origin policy. Because the server can determine whether to allow this communication based on this field. If the domain name is in the whitelist, the server will respond as follows.
remove

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat

3.CORS
CORS is a W3C standard, the full name is "Cross-origin resource sharing" (Cross-origin resource sharing). It allows browsers to issue XMLHttpRequest requests to cross-origin (protocol + domain name + port) servers, thus overcoming the limitation that AJAX can only be used with the same origin. Compared to JSONP, which can only send GET requests, CORS allows any type of request.
The key to implementing CORS communication is the server. Cross-origin communication is possible as long as the server implements the CORS interface

Basic Process
Browsers divide CORS requests into two categories: simple requests and not-so-simple requests .

Simple request: just add an Origin field to the header.

Non-simple request: An HTTP query request will be added before the formal communication, which is called a "preflight" request (preflight). The browser first asks the server whether the domain name of the current page is on the server's allow list, and which HTTP verbs and header fields can be used. The browser will issue a formal XMLHttpRequest request only if it gets a positive answer, otherwise it will report an error.

只要同时满足以下两大条件,就属于简单请求。
1) 请求方法是以下三种方法之一:
HEAD
GET
POST
2)HTTP的头信息不超出以下几种字段:
Accept
Accept-Language
Content-Language
Last-Event-ID
Content-Type:只限于三个值application/x-www-form-urlencoded、multipart/form-data、text/plain

The implementation method under nodejs:

router.get('/getData', function(req, res, next) {  
  //设置允许跨域请求  
  var reqOrigin = req.header("origin");  
  res.header("Access-Control-Allow-Origin", "http://localhost:3000");  
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");  
  res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");  
  res.json(200, {name:"张三1",age:40});  
  }  

Configuration item explanation
Access-Control-Allow-Origin
This field is required. Its value is either the specific value of the Origin field at the time of the request, or a *, indicating that requests from any domain name are accepted.

Access-Control-Allow-MethodsThis
field is required. Its value is a specific string separated by commas or *, indicating all methods supported by the server for cross-domain requests. Note that all supported methods are returned, not just the one requested by the browser. This is to avoid multiple "preflight" requests.

Access-Control-Expose-Headers
This field is optional. When a CORS request is made, the getResponseHeader() method of the XMLHttpRequest object can only get 6 basic fields: Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, and Pragma. If you want to get other fields, you must specify them in Access-Control-Expose-Headers.

Access-Control-Allow-Credentials
This field is optional. Its value is a boolean value indicating whether to allow cookies to be sent. By default, cookies do not occur, ie: false. For requests with special requirements to the server, such as the request method is PUT or DELETE, or the type of the Content-Type field is application/json, this value can only be set to true. If the server does not want the browser to send cookies, just delete this field.

Access-Control-Max-Age
This field is optional and is used to specify the validity period of this preflight request, in seconds. During the validity period, another preflight request is not issued.

Note:
a. All browsers support this function, IE browser cannot be lower than IE10
b. When CORS requests to send cookies, Access-Control-Allow-Origin can only be the domain name consistent with the requested webpage. At the same time, cookies still follow the same-origin policy. Only cookies set with the server domain name will be uploaded, and cookies of other domain names will not be uploaded, and the document.cookie in the (cross-origin) original web page code cannot be read under the server domain name. Cookies.

4. Set up a server proxy
The browser requests the same-origin server, and the latter requests external services

Guess you like

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