Front end basic arrangement | network related (2)

Time:2020-5-28

First address: http://www.brandhuang.com/article/1585139147636

Cross domain

In the development mode of front-end and back-end separation, cross domain problems often occur,The front end sent the request and the server responded, but the front end could not get the response

Why does the server respond correctly, but the front end can’t get the response?

Because browsers follow oneSame origin policy (if the protocol, host and port are the same, then the same origin)。 For non homologous sites, browsers have some restrictions:

  • Unable to read and modify the dom of the other party
  • Do not read cookies, indexdb, and localstorage
  • Limit XMLHttpRequest requests.

When the browser makes an Ajax request to the server, if the current URL and the target URL are different from the source, thenCross domain request

The response of cross domain request will be blocked by the client(Note: the response has been obtained by the client, but it is blocked

Handling cross domain CORS

CORS is a W3C standard, full nameCross domain resource sharing。 Support non IE and ie10 or above.Specific response headers need to be attached to the server

According to the request method and specific fields of the request header, the browser divides the request intoSimple requestandNon simple request。 Different processing for these two kinds of different requests

Simple request

The simple request meets the following conditions:

  • The request method is get, post or head
  • The value range of the request header: accept, accept language, content language, and content type (only three valuesapplication/x-www-form-urlencoded、multipart/form-data、text/plain)

Before the request is sent out, the browser addsOriginField, server adds in responseAccess-Control-Allow-OriginField, if this field is not inOriginField, the browser intercepts the response. So,Access-Control-Allow-OriginField is used by the server to determine whether the browser will intercept the response. This is a required field.

Access-Control-Allow-CredentialsIs a Boolean value indicating whether cookies are allowed to be sent. Browser pairThe default value of this field is set to false, to request the browser to carry cookies, you need to add the response header and set it to true, and you need to set the withcredentials property to true in the front end,

let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
Non simple request

Requests other than simple requests (put delete patch, etc.)

When a non simple request is initiated, it will be initiated firstPre check requests (options), plusOriginSource address andHostTarget address, plus two key fields:

  • Access control request method, which HTTP method is used for CORS request
  • Access control request headers, which specifies what request headers will be added to CORS requests

The response to the pre inspection request is as follows:

HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: X-Custom-Header
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 1728000
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Content-Length: 0

After the response of the pre check request returns, if the request does not meet the conditions of the response header, triggerOne error of XMLHttpRequestMethod, of course, the real CORS request will not be sent.

Handle cross domain jsonp

Principles: dynamic creationscriptTag, it can fill in the target address through SRC to send out get request, realize cross domain request and get response

Comparison of jsonp and CORS

andCORScomparison,JSONPThe biggest advantage is good compatibility, ie low version can not be usedCORSBut it can be usedJSONPThe disadvantages are obvious. The request method is single and only supports get requests.

Processing cross domain | nginx

The server is configured as follows:

server {
  listen  80;
  server_name  client.com;
  location /api {
    proxy_pass server.com;
  }
}

Processing cross domain | PostMessage

MDN document: window.postMessage

otherWindow.postMessage(message, targetOrigin, [transfer]);

window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
  // For Chrome, the origin property is in the event.originalEvent
  // object. 
  //It's not accurate here. Chrome doesn't have this property
  // var origin = event.origin || event.originalEvent.origin; 
  var origin = event.origin
  if (origin !== "http://example.org:8080")
    return;

  // ...
}

For a more detailed explanation, please refer to the article of the God ternary: https://juejin.im/post/5e76bd516fb9a07cce750746#heading -67

The main ways of instant communication

Instant messaging, an instant messaging service based on the Internet..

There are four ways to achieve instant messaging:Short pollingLong poll (comet)Long connection (SSE)WebSocket

The above four categories can be divided into two categories:

  • Based on http: short polling, long polling, long connection
  • Non http: websocket

Short polling

Basic realization ideas:The browser sends the HTTP request to the server at regular intervals, and the server responds immediately after receiving the request (no matter whether the content changes or not). The TCP connection is closed after the response is complete.

Long poll (comet)

Basic realization ideas:When the server receives the request from the client, it will not respond directly, but first suspend the request, and then judge whether the data on the server is updated. If there is an update, respond. If there is no data all the time, close the connection after reaching a certain time limit (server-side setting).

Compared with short polling, long polling,Reduced the number of unnecessary HTTP requests。 But long pollingConnection stuckIt also leads to waste of resources.

Long connection (SSE)

View MDN documents

What’s new in HTML5,Initiated by clientCreate a TCP connection to the server and maintain it until either the client or the server disconnects. After the connection is created, the browser periodically sends a message to the server to ask
。 HTTP response content has a specialcontent-type —— text/event-streamThe response header identifies the response content asEvent flow, clientConnection will not be closedInstead, wait for the server to send the response results continuously.

use:

var source = new EventSource('/XXX');
  //Default events
  source.addEventListener('message', function (e) {
      console.log(e.data);
  }, false);

  //User defined event name
  source.addEventListener('my_msg', function (e) {
      process(e.data);
  }, false);

  //Monitor connection on
  source.addEventListener('open', function (e) {
      console.log('open sse');
  }, false);

  //Listening error
  source.addEventListener('error', function (e) {
      console.log('error');
  });

Websocket

Websocket is a new protocol defined by HTML5. Different from the traditional HTTP protocol, it can realize the server and clientTwo way simultaneous communication (full duplex communication)

First, let the client and the server establish a connection through HTTP. After the connection is established, the HTTP protocol is no longer used, and data can be transferred.

const socket = new WebSocket('ws://localhost:8080');

// Connection opened
socket.addEventListener('open', function (event) {
    socket.send('Hello Server!');
});

// Listen for messages
socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
});

CDN

Full namecontent delivery network, content distribution network. Is a group of servers distributed in different geographical locations. According to the actual location of the user, the CDN server closest to the user provides the user with content, improves the access speed and improves the user experience.

It is mainly used to solve network congestion, improve access speed, and solve the problem of slow access speed caused by small network bandwidth, large user access volume and uneven node distribution.

General principle of CDN:

  1. The user enters the domain name to be accessed in the browser;
  2. For domain name resolution, CDN adjusts the domain name resolution process, so the resolution function library is generallyThe CNAME record corresponding to the domain name is obtainedIn order to get the actual IP address, the browser needs toResolve the CNAME domain name obtainedTo get the actual IP address; in this process, use the global load balancing DNS resolution. For example, the corresponding IP address is resolved according to the geographic location information, so that users can access it nearby;
  3. This resolutionGet the IP address of CDN cache serverAfter getting the actual IP address, the browser sends the access request to the cache server;
  4. According to the domain name to be accessed provided by the browser, the cache server resolves through the internal dedicated DNS of cacheGet the actual IP address of this domain name, and then the cache server submits the access request to the actual IP address;
  5. After the cache server obtains the content from the actual IP address, on the one hand, it saves it locally for future use; on the other hand, it puts the acquired data back to the client to complete the data service process;
  6. After the client gets the data returned by the cache server, it will display and complete the data request process of browsing.

This article first arranges so many, anyway one time also cannot digest.

If you like this article, I hope you can like it

Of course, you can follow me to get the follow-up articles

You can also follow my personal blog

You can also focus on my official account, “Chongqing cubs after 90”.

Front end basic arrangement | network related (2)