Front-end fetch communication


Abstracts from this article to: please call me HR

With the development of front-end asynchronism, the writing of XHR is not conducive to Front-end asynchronous Promise callback. Moreover, it is very complex to write. The fetch API was originally proposed in SW (Service Workers), but later, when it feels useful, it is mounted under the window object. In this way, we can also call it directly in the normal communication of front-end. However, fetch is relatively new after all. Look at his compatibility.

Front-end fetch communication

On the PC side, comparing fashion. mobile with FF, Opera and Chrome, it is basically useless. Of course, the front end has always been a career embracing change, and the official has a ready-made Polyfill to use. In this case, there is no need to worry too much.

Every time we use a new feature, we first know if it can be used. Modernizr is a good library. Here, let’s have a brief look at it.

let isFetch = window.fetch?true:false;

Fetch basic format

It can be said that fetch is Ajax + Promise. It is used in a way similar to the $. Ajax () provided by jquery.

    function(response) {  
      if (response.status !== 200) {  
        Console. log (`Return response code ${response. status}');  

      // Get the content actually returned from the background
      response.json().then(function(data) {  
  .catch(function(err) {  
    console.log('Fetch Error :-S', err);  

The demo above has very good parameters, several features of fetch.

  • then()

  • catch()

  • json()

Then and catch are two methods of promise. I won’t talk about them here. Let’s see what JSON is for.

Because the data returned includes not only the text content returned from the background, but also some headers. So, the res returned from the then method is not actually what we want in the business. It’s the same as returning data from XHR. What we want in the end isresponseTextThis data. What the JSON () method actually does is call JSON. parse () to process the data and return a new Promise. Look at the Polyfill source code.

this.json = function() {
    return this.text().then(JSON.parse)

Fetch transmission format

The demo above is a request for get method. Of course, besides get, there are other HTTP methods, PUT, DELETE, POST, PATCH and so on. Here, we will talk about a POST. The basic format of other methods is similar.

fetch("", {
  method: "POST",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  body: "this is a post Msg"
}).then(function(res) {
  if (res.ok) {
    // doSth
  } else if (res.status == 401) {
    // doSth

It seems that fetch is not much different from $. ajax.
But… there’s a lot of content in fetch. Looking at the bottom, fetch is actually an integration of Request, Headers and Response interfaces. However, these three interfaces can only be used in SW. Here as a principle, just a few parameters.

Headers operation

The operation of headers is nothing more than CRUD. Here I will just go into more details and look at the code directly.

var content = "Hello World";
var reqHeaders = new Headers();
reqHeaders.append("Content-Type", "text/plain"
reqHeaders.append("Content-Length", content.length.toString());
ReqHeaders. append ("X-Custom-Header", "Custom Header");

Of course, you can also use literal quantities:

reqHeaders = new Headers({
  "Content-Type": "text/plain",
  "Content-Length": content.length.toString(),
  "X-Custom-Header": "Custom Header"

Next, the detection of the content of the head is relevant.

console.log(reqHeaders.has("Content-Type")); // true
console.log(reqHeaders.has("Set-Cookie")); // false
reqHeaders.set("Content-Type", "text/html");
ReqHeaders. append ("X-Custom-Header", "New Custom Header");
console.log(reqHeaders.get("Content-Length")); // 11
Console.log (reqHeaders.getAll ("X-Custom-Header"); //["Custom Header", "New Custom Header"]
console.log(reqHeaders.getAll("X-Custom-Header")); // []

However, due to security considerations, sometimes header restrictions are required for multi-person collaboration or sub-block management. Here, we can go throughguardProperty to set headers’policies.
Guard can usually take “immutable”, “request”, “request-no-cors”, “response”, “none”.
Let’s not go into all of this here, just look at the request option.
When you set the request, if the header you set involves the forbidden header name (which is automatically set by the browser), the operation will not succeed.
Forbidden header name usually has.

  • Accept-Charset

  • Accept-Encoding

  • Access-Control-Request-Headers

  • Access-Control-Request-Method

  • Connection

  • Content-Length

  • Cookie

  • Cookie2

  • Date

  • DNT

  • Expect

  • Host

  • Keep-Alive

  • Origin

  • Referer

  • TE

  • Trailer

  • Transfer-Encoding

  • Upgrade

  • Via

Compared with fetch, we can’t set guard for Headers, so it can only be used in SW.

Request operation

The basic usage of Request is similar to fetch.

var uploadReq = new Request("/uploadImage", {
  method: "POST",
  headers: {
    "Content-Type": "image/png",
  body: "image data"

fetch("/uploadImage", {
  method: "POST",
  headers: {
    "Content-Type": "image/png",
  body: "image data"

In browsers, all requests can’t escape cross-domain and non-cross-domain problems. So does fetch. For cross-domain requests, the main impact is reflected in Response, which has little impact. However, we need to set up fetch.modeProperty to indicate that this is a cross-domain request.

fetch('', {mode: 'cors'})  
  .then(function(response) {  
    return response.text();  

The commonly used model attribute values are:

  • Same-origin: Represents requesting only the same domain. If you make cross-domain requests under this model, you will report an error.

  • No-cors: Normal network requests, mainly for no background and no settingsAccess-Control-Allow-OriginIn other words, it is used to handle script, image and other requests. It is the default value of mode.

  • Cors: Used to send cross-domain requests. When sending requests, you need to bring them with you.

There is also a cross-domain content about cookies. In XHR2, we learned that with Credentials is a property used to set whether or not servers in different domains send cookies in different domains during cross-domain operations. It is generally set to omit (not sent). In fetch, the use iscredentialsAttributes.
Credentials are commonly used as:

  • Omit: When sending a request, do not bring cookie. Default value.

  • Same-origin: When sending a request for the same domain, a cookie is brought with it.

  • Include: Whenever you send a request, you bring a cookie with you.

So, if you want to send Ajax with cookies, you need to use the same-origin. If you want to bring cookies across domains, you need to include.

// Cross-domain requests
fetch('', {mode: 'cors',credentials:'include'})  
  .then(function(response) {  
    return response.text();  

Response operation

Response should be the closest object to fetch. Response is actually the parameter returned by fetch callback function. There are four commonly used attributes in Response: status, status Text, ok, type.

  • Status: Return status code. 100-500+

  • StatusText: The meaning of a return status code. For example, return “ok”.

  • OK: used to check whether the status is between 200 and 299.

  • Type: Indicates whether the request is cross-domain or error-prone. Values are: “basic”, “cors”, “default”, “error” or

fetch('', {mode: 'cors',credentials:'include'})  
  .then(function(response) {  
    // ...

Here, we focus on some of the attributes mounted on the type.

  • Basic: The same domain communication category. You can normally access the header of response (except Set-Cookie header).

  • Cors: Cross-domain communication category. Usually only the following headers can be accessed:

    • Cache-Control

    • Content-Language

    • Content-Type

    • Expires

    • Last-Modified

    • Pragma

  • Error: Network Error Category.

  • Opaque: Unable to understand categories. When usedno-corsWhen a cross-domain request is sent, it triggers.

In addition, several commonly used methods are mounted on response: text (), JSON ().

  • Text (): Mainly used to process string type data returned by server.

  • Josn (): Mainly used to process JSON type data returned by server.

Flow API is the way to use it.

  .then(function(res) {  

The basic content is the above. If you want to refer to it in more detail, please consult:

This API is so Fetching!