Preface 🎤

This article summarizes common web requests in browsers. Json isn’t.

Ajax

It’s a cliche that Ajax does not support cross-domains.

function ajax(method,url,cb,data = {}){
    let u = new URL(url)
    let dataRaw = ' '
    if(method.toLowerCase() == 'get') {Object.keys(data).forEach((key) = >u.searchParams.set(key,data[key]))
    }else{
        dataRaw = Object.keys(data).map((key) = >`${key}=${data[key]}`).join('&')}let xhr = new XMLHttpRequest
    xhr.onreadystatechange = function(){
        if(xhr.readyState === 4) {if(xhr.status === 200 || xhr.status === 304)
                return cb(xhr.responseText)
            throw new Error(xhr.status)
        }
    }

    xhr.open(method,u.toString(),false)
    if(method.toLowerCase() == 'post'){
        xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded')
    }
    xhr.send(dataRaw)
}
Copy the code

A few points to note are:

  • You need to set the header when you send a POST
  • The request is complete only if readyState is 4
  • Again, errors won’t be known until readyState is 4

Fetch

Fetch is a high-level encapsulated network request method provided by modern browsers. It allows you to create web requests in a very concise and elegant way. Cross-domain support.

fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });
Copy the code

The forced interrupt of Fetch

Fetch has a Singal feature that allows developers to force interrupts of requests, though this feature is not spotty.

let controller = new AbortController()
fetch('http://example.com/movies.json', {signal:controller.signal})
Copy the code

Long polling

Long polling is a smart and ingenious polling method, which can reduce the network occupation caused by polling and ensure the timeliness of the message. Long polling operates in much the same way as normal polling, except for the return control of the server. This requires the server program to support pending links, which in general can be supported by various back-end programs. When a client initiates a request, the back end accepts the request and waits for a long time until certain conditions are met before data is returned. For example, the client needs to listen for the user to click on the activation link in the mailbox, and when the request is made, the back end will suspend the front-end request until the user clicks on the activation link and it is activated. The front end then decides whether to continue making requests based on the requirements.

This request mode is generally used when the number of messages is small. If the number of messages increases, WebSocket or Server Send Events can be used.

Server Send Events

Server Send Events is an early one-way data transmission scheme (but IE still does not support it). It allows a subscription mode for the server to continuously transfer data to the client. This method requires retrofitting of the front and back ends and is not a direct and painless solution. It is also an HTTP request. Cross-domain support.

Initiating event flow

let eventSource = new EventSource("https://www.example.com/index.php")
Copy the code

Receive data

The server needs to use a special format to write

//etc
data: hello? 

data: i am
segment

data: ok
Copy the code

As shown above, the data needs to be separated with \n\n to count as an information segment. Also start with data:.

The client does

eventSource.onmessage = function(ev){
    console.log(ev.data)
}
// or addEventListener
Copy the code

Not only that, we don’t have to deal with disconnection cases, the client will help us reconnect automatically, which is an advantage WebSocket doesn’t have. However, some error status codes are encountered (except :200.301,307), or headers are not content-Type: text/event-stream. Is not reconnected.

If you want to disconnect actively, use evnetsource.close ().

Message ID

In general, each message should be accompanied by an ID: for example:

data: hello
id: 1

data: world
id:2

Copy the code

When the browser detects content with an ID, it automatically updates eventsource.lasteventid. In addition, a last-event-ID header is set for line breaking and reconnection.

Server Sent Events is lighter in functionality than WebSocket, but can work well in some special scenarios.

WebSocket

The great WebSocket is one of the core network request functions in the front end. For real-time high network applications, it is a ground-breaking initiative, which marks the birth of web multiplayer games without dependence network layer, marks the victory of front-end trading system possibility, marks the front-end game frameless developers stand up from now on! WebSocket uses a special protocol that usually begins with ws:// or WSS ://. A WebSocket object has four kinds of basic events, the open, the message, the error, the close. If you want to send data, you can do so using.send(). Cross-domain support.

Because the difficulty of using WebSocket has reached an outrageously easy level, simple content is no longer described. And WebSocket fame and popularity has reached a new level, if you say that you are the front-end does not know WebSocket, then it is really likely to laugh.

Conclusion 👨 🏫

Ajax was the earliest form of web request in the browser, and before that JS was just a web toy. With the progress and development of Events, Server Send Events, a more advanced information transmission method, emerged. Later, fetch and WebSocket, two new functions of benchmarking Ajax and Server Send Events, were provided by modern browsers. The speed of Internet development seems to turn on the accelerator general strides forward.