HTTP requests in the browser

XMLHttpRequest

XHR objects are used to interact with the server. XMLHttpRequest allows you to retrieve data by requesting a specific URL without refreshing the page. XMLHttpRequest is widely used in Ajax programming.

MDN document

Fetch

The FETCH API provides an interface for fetching resources (including cross-domain requests)

MDN document

AJAX

Asynchronous JavaScript And XML, is a programming practice that uses XMLHttpRequest technology to build more complex, dynamic web pages. Much of Ajax is about encapsulating the XMLHttpRequest API to make it easier to use.

MDN document

Cross domain

Crossdomain, as the name implies, across regions. The website you are visiting requests a resource that is not of the same origin.

URL of current page The requested resource URL Cross domain why
http://www.test.com http://www.test.com/api/users no Same origin (same protocol domain name port number)
http://www.test.com https://www.test.com/api/users is Different protocols (HTTP/HTTPS)
http://www.test.com http://www.baidu.com/api/users is Primary domain name is different (test/baidu)
http://www.test.com http://blog.test.com/api/users is Different subdomain names (WWW /blog)
http://www.test.com:8080 http://www.test.com:7070/api/… is Different port numbers (8080/7070)

Why is there cross-domain

Ask why in advance. So why do browsers set cross-domain restrictions and then go to the trouble of removing them later?

For the security of the Web ecosystem. Consider an example:

Assuming that the browser code can freely access third-party data (noncognate), then you can make your code regularly polling access a web page, the homologous suppose sometime happens to have 100000 people on a visit to your web page, that the third-party web pages per second will bear the concurrency value of 100000, so a lot of bandwidth in the network is so white waste, The entire web ecosystem would be in chaos.

When visiting websites that need to request non-same-origin resources, the browser will reject those non-same-origin requests. In this case, we need to address the limitation of the browser rejecting requests for non-cognate resources across domains.

When browsers cross domains, two key concepts are inevitably introduced. Simple and non-simple requests.

When cross-domain generation occurs, non-simple requests are pre-checked (OPTIONS) before they are actually sent to the server.

A simple request

1, condition definition: if the request meets all the following conditions, the request can be regarded as a simple request.

  • Use one of the following methods:
  • GET
  • HEAD
  • POST
  • The request header field must not exceed the following collection
  • Accept
  • Accept-Language
  • Content-Language
  • Conent – Type: text/plain | | multipart/form – data | | application/x – WWW – form – urlencoded
  • DPR
  • Downlink
  • Save-Data
  • Viewport-Width
  • Width
  • None of the XMLHttpRequestUpload objects in the request have registered any event listeners
  • The ReadableStream object is not used in the request

Nonsimple request

1, condition definition: if the request meets any of the following conditions, the pre-check request (OPTIONS) should be sent first.

  • Either of the following methods is used:
  • PUT
  • DELETE
  • CONNECT
  • OPTIONS
  • TRACE
  • PATCH
  • Additional request header fields are set (except in the following collections)
  • Accept
  • Accept-Language
  • Content-Language
  • Conent – Type: text/plain | | multipart/form – data | | application/x – WWW – form – urlencoded
  • DPR
  • Downlink
  • Save-Data
  • Viewport-Width
  • Width
  • An arbitrary number of event listeners are registered with the XMLHttpRequestUpload object in the request
  • The ReadableStream object was used in the request

Solve cross-domain solutions

jsonp

JSON with Padding is a way of using JSON to allow a web page to fetch data from another domain. Because of the same origin policy, in general, Web pages located at server1.example.com cannot communicate with servers that are not server1.example.com, with the exception of the

Because of the SRC attribute of the script tag, only the GET method is supported.

When using a scheme like JSONP, the front and back ends need to be written accordingly. Process is roughly, front end through the SRC attribute of the < script > tag to the backend interface request (only support a GET request), and pass parameters callback = ‘response’, at the same time, the front must be defined function response (responseData), This is used to handle the data returned by the interface after some operations. When the interface receives a request, it returns data in the format of response(responseData). In this way, the current end receives the data response(responseData) and executes the response(…) we have already defined.

When the following error is reported:



The reason: the backend interface did not returncallback(...)

wikipedia

The principle and implementation of JSONP

CORS

Cross Origin Resource Sharing, cross-domain Resource Sharing, consists of a series of transmitted HTTP headers that determine whether the browser prevents front-end JavaScript code from obtaining responses to cross-domain requests.

MDN document

1, Access-Control-Allow-Origin: Indicates to which domains the requested resource can be shared

Access-Control-Allow-Credentials: Indicates whether to respond to a request when its Credentials are marked true

Access-Control-Alone-HEADERS: Which HTTP methods Allow Access to the requested resource in response to a pre-request

Access-Control-Expose-headers: Indicates which HTTP header names can be listed in the response

5, Access-Control-Max-Age: Indicates how long the pre-requested results can be cached

Access-Control-Request-Headers: This is used to make a pre-request that tells the server which HTTP Headers will be used for the formal Request

7, Access-Control-Request-Method: This is used to initiate a pre-request that tells the server which HTTP Request Method will be used for the formal Request

8. Origin: Indicates from what domain the request for the resource was made

The KOA2 interface allows cross-domain responses. The response header field is set as follows:

ctx.set('Access-Control-Allow-Origin', '*');
ctx.set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT');
ctx.set('Access-Control-Allow-Headers', 'X-Requested-With, User-Agent, Referer, Content-Type, Cache-Control,accesstoken');  
ctx.set('Access-Control-Max-Age', '86400');
ctx.set('Access-Control-Allow-Credentials', 'true');

Note: If you add a custom Header field, you must add the field name to Access-Control-Alallow Headers in the server response Header, otherwise an error will be reported.

Response to preflight request doesn’t pass access control check: Added the above header field to the interface Response that allows cross-domain responses, but reported a cross-domain error during development (Response to preflight request doesn’t pass access control check: Redirect is not allowed for a preflight request. Redirect is not allowed for a preflight request. The request was redirected to HTTPS by HTTP + IP address. However, the precheck request made by the browser is not allowed to redirect to HTTPS, so an error was reported. The solution is to change the request address to HTTPS + domain name so that the precheck request does not redirect.