Writing in the front

  • I wrote an AJAX related blog before, and saw some friends talking about Fetch, so I did some research

  • Blog content reference:

    • www.ruanyifeng.com/blog/2020/1…
    • Developer.mozilla.org/en-US/docs/…
    • Github.com/node-fetch/…
    • Github.com/github/fetc…
  • Demo builds a simple Flaskweb service and makes requests through the Node environment

Now you are in the desert, so you need to be in the desert. The desert, like anything else in the world, can be used to understand the world. You don’t even have to understand the desert, just look at ordinary grains of sand, and you can see the wonders of the universe. ——– The Shepherd Boy’s Journey


The Fetch API provides an interface to Fetch resources (including cross-domain requests). Anyone who has ever worked with XMLHttpRequest should be able to get started, and the new API offers a much more powerful and flexible set of features.

Fetch provides a common definition of Request and Response,Headers (and other objects related to network requests)

Fetch () must take one argument — the path to the resource. Whether the request succeeds or fails, it returns a Promise object, resolve corresponding to the Response of the request. You can also pass an optional second parameter init.

Once the Response is returned, you can use methods to define what form the content should take and how it should be handled. You can also create the Request and Response directly through the Request() and Response() constructors, but we don’t recommend this.

The Fetch interface

  • Headers: is equivalent to the response/ Request header
  • Request: represents a resource request
  • Response: is the response to a request

Using the Fetch

The Fetch API provides a JavaScript interface for accessing and manipulating specific parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method, which provides a simple, reasonable way to fetch resources asynchronously across a network.

The fetch specification differs from jquery.Ajax () in the following key ways:

  • When an error is receivedThe HTTP status codeIs returned from fetch()PromiseWill not be marked as reject, even if the responseThe HTTP status codeis404 or 500. Instead, it willPromiseThe status is marked asresolve (If the HTTP status code of the response is not in the range of 200-299, set the OK attribute of the resolve return value to false.), flagged only when the network fails or the request is blocked reject.

Fetch does not send cross-domain cookies unless you use the initialization option of credentials. The default credentials policy has been changed to same-Origin since August 2018. Firefox has also been modified in version 61.0b13)

  • fetch()usePromiseAnd don’t useThe callback functionSo it’s a lot simpler, it’s a lot simpler to write.
  • fetch()usingModular design, the API is scattered over multiple objects (Response object, Request object, Headers object), more reasonable; By contrast,XMLHttpRequestAPI design is not very good, input, output, state are managed in the same interface, easy to write very messy code.
  • Fetch () processes data through a data Stream (Stream object), can be read in chunks, which is conducive to improving website performance and reducing memory footprint. It is useful for large file requests or slow network speed scenarios. The XMLHTTPRequest object does not support data streaming. All data must be stored in the cache. It cannot be read in chunks.

In usage, fetch() takes a URL string as an argument, and by default makes a GET request to the URL, returning a Promise object.

Environment to prepare

Here we use the Node environment to learn, of course, in the browser is more comparable, need to install node-based dependency package Node-FETCH, here must pay attention to version issues

  • node-fetchUsed forThe server side, that is, only withinnodejsusing
  • whatwg-fetchUsed forThe clientIs used inFetch is not natively supported by browsersIn the case
  • isomorphic-fetchCan be found innodejsandThe browserRunning in both environments, rightwhatwg-fetchthepackaging.
npm install node-fetch@2
Copy the code

We also need a Web service for testing, which is a simple Web service built with Python

#! /usr/bin/env python3
# -*- encoding: utf-8 -*-
# Python 3.9.0
# pip install flask
"@file: fetch. Py @time: 2022/03/04 18:59:02 @author: Li Ruilong @version: 1.0 @contact: [email protected] @desc: Fetch learning Demo ""

from time import sleep
from flask import Flask,jsonify,request,send_from_directory
import os

# configuration
DEBUG = True

app = Flask(__name__)



@app.route("/")
@app.route("/index")
def default() :
    "@time: 2022/03/04 18:58:42 @author: Li Ruilong @version: 1.0 @desc: Default page"
    return "< h1 > Fetch learning Demo < h1 / >"

@app.route('/init', methods=['GET'])
def init() :
    @time: 2022/03/04 19:41:40 @author: Li Ruilong @version: 1.0 @desc: GET request returned JSON ""
    
    data = ["Ajax"."Fetch"."Promise"."Axios"]
    return jsonify(data)

@app.route("/add",methods=["POST"])
def add() :
    "@time: 2022/03/04 19:43:05 @author: Li Ruilong @version: 1.0 @desc: Post request"
    data = request.json
    print(*data, sep='\n')
    return jsonify({"msg":"Post request successful"."code":"0"})


@app.route("/download/<filename>")
def download(filename) :
    print(filename)
    "@time: 2022/03/04 22:30:12 @author: Li Ruilong @version: 1.0 @desc: Download file"
    directory = os.getcwd()  
    print(directory)
    return send_from_directory(directory, filename, as_attachment=True)


@app.route('/upload', methods=['POST'.'PUT'])
def upload() :
    "@time: 2021/12/15 10:32:03 @author: Li Ruilong @version: 1.0 @desc:"
    if request.method == 'POST':
        try:
            f = request.files['file']
            print("Upload file name :===", f.filename)
            basepath = os.path.dirname(__file__)  # Path of the current file
            upload_path = os.path.join(basepath, "\ \".str(f.filename))  
            f.save(upload_path)
            print("Save file path:"+upload_path)
        except Exception as e:
            print("Failed to upload file", e)
    return jsonify({"msg":"Upload file OK"."code":"0"}),200

@app.route("/stop/<int:s>")
def stop(s) :
    sleep(s)
    return "OK".200


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=37881, debug=DEBUG)

Copy the code

Data. The json file

[{"site": "npr"."link": "http://www.npr.org/rss/rss.php?id=1001"."type": "rss"
	},
	{
		"site": "npr"."link": "http://www.npr.org/rss/rss.php?id=1008"."type": "rss"}]Copy the code

With the preparation done, let’s begin our study happily

A basic FETCH request is simple to set up. Look at the following code:

This is a callback style request to get JSON data from the server. A Demo in the Node environment

// -*- encoding: utf-8 -*-

/* * @file: fetch. Js * @time: 2022/03/04 22:04:04 * @author: Li Ruilong * @version: 1.0 * @contact: [email protected] * @desc: Fetch learning */
const fetch = require("node-fetch");

fetch('http://127.0.0.1:37881/download/data.json')
  .then(response= > response.json())
  .then(json= > console.log(json))
  .catch(err= > console.log('Request Failed', err)); 
Copy the code

Fetch () receives Response as a Stream object, and Response.json () is an asynchronous operation that fetches everything and turns it into a JSON object.

It is similar to Axios in that it is based on ES 6 Promise objects. In the Node environment, it is based on HTTP modules. Fetch is a new API that implements asynchronous communication based on XMLHttpRequests. Fetch is the latest alternative to XMLHttpRequest. Here is an example of AXIOS.

const axios = require('axios').default;
const { v4: uuidv4 } = require('uuid');

let subscriptionKey = "3c6588c7026b41a4**7f81551cb4a737";
let endpoint = "https://api.translator.azure.cn/";


let location = "chinanorth";

axios({
    baseURL: endpoint,
    url: '/translate'.method: 'post'.headers: {
        'Ocp-Apim-Subscription-Key': subscriptionKey,
        'Ocp-Apim-Subscription-Region': location,
        'Content-type': 'application/json'.'X-ClientTraceId': uuidv4().toString()
    },
    params: {
        'api-version': '3.0'.'from': 'zh-Hans'.'to': ['zh-Hant'.'en']},data: [{
        'text': 'I learned in vain to resist the bustle, but I have not yet had time to understand the real silence. -------- Zhang Dachun '}].responseType: 'json'
}).then(function(response){
    console.log(JSON.stringify(response.data, null.4));
}).catch(function (error) {
    console.log(error);
  });

Copy the code

Promises can be rewritten with await syntax to make the semantics clearer.

// -*- encoding: utf-8 -*-

/* * @file: fetch. Js * @time: 2022/03/04 22:04:04 * @author: Li Ruilong * @version: 1.0 * @contact: [email protected] * @desc: Fetch learning */


const fetch = require("node-fetch");

(async() = > {let url = 'http://127.0.0.1:37881/download/data.json';
    try {
        let response = await fetch(url);
        let data =await response.json();
        console.log(data);
    } catch (e) {
        console.log("Oops, error", e);
    }
})()

Copy the code

Await statement must be placed in try… Catch in order to catch errors that may occur during asynchronous operations.

=====
PS D:\GolandProjects\code-master\demo> node fetch
[
  {
    site: 'npr',
    link: 'http://www.npr.org/rss/rss.php?id=1001'.type: 'rss'
  },
  {
    site: 'npr',
    link: 'http://www.npr.org/rss/rss.php?id=1008'.type: 'rss'
  }
]
PS D:\GolandProjects\code-master\demo> 
Copy the code

Response object: Handles HTTP responses

After the fetch() request succeeds, a Response object is returned. It corresponds to the HTTP response from the server.

const response = await fetch(url);
Copy the code

Response contains the DE synchronization attribute, which corresponds to the Headers of the HTTP Response and can be read immediately

// -*- encoding: utf-8 -*-

/* * @file: fetch. Js * @time: 2022/03/04 22:04:04 * @author: Li Ruilong * @version: 1.0 * @contact: [email protected] * @desc: Fetch learning */

const fetch = require("node-fetch");

(async() = > {let url = 'http://127.0.0.1:37881/init';
    try {
        let response = await fetch(url);
        // The synchronization attribute, which corresponds to the Headers of the HTTP response, can be read immediately
        console.log(response.ok);
        console.log(response.status); 
        console.log(response.statusText);
        console.log(response.type);
        console.log(response.url);
        console.log(response.redirected)
        //Response contains data that is read asynchronously through the Stream interface
        let data =await response.json();
        console.log(data);
    } catch (e) {
        console.log("Oops, error", e);
    }
})()
Copy the code
[Running] node "d:\GolandProjects\code-master\demo\fetch.js"
true
200
OK
undefined
http://127.0.0.1:37881/init
false
[ 'Ajax'.'Fetch'.'Promise'.'Axios' ]

[Done] exited with code=0 in 0.253 seconds
Copy the code

Response. ok: The property returns a Boolean value indicating whether the request was successful, true for HTTP request status codes 200 through 299, false for any other status code.

Response.status: Property returns a number representing the status code of the HTTP response (for example, 200 for a successful request).

Response.statustext: Property returns a string representing the status of the HTTP response (for example, the server returns “OK” after a successful request).

Response. url: Property returns the requested URL. This property returns the final URL if there is a jump to the URL.

Response.type: The type of request the property returns. Possible values are as follows:

Check whether the request is successful based on the status code

// -*- encoding: utf-8 -*-

/* * @file: fetch. Js * @time: 2022/03/04 22:04:04 * @author: Li Ruilong * @version: 1.0 * @contact: [email protected] * @desc: Fetch learning */

const fetch = require("node-fetch");

(async() = > {let url = 'http://127.0.0.1:37881/init';
    try {
        let response = await fetch(url);
        if (response.status >= 200 && response.status < 300) {let data = await response.json();
            console.log(data);
            return data;
        }else{
            console.log(response.statusText);
            throw new Error(response.statusText); }}catch (e) {
        console.log("Oops, error", e);
    }
})()
Copy the code

We throw an exception in Python’s Web services interface and throw it directly into a catch

@app.route('/init', methods=['GET'])
def init() :
    @time: 2022/03/04 19:41:40 @author: Li Ruilong @version: 1.0 @desc: GET request returned JSON ""
    
    data = ["Ajax"."Fetch"."Promise"."Axios"]
    raise Exception('This is a mock request exception')
    return jsonify(data)
Copy the code

Execution error: internal server error, i.e. 500

[Running] node "d:\GolandProjects\code-master\demo\fetch.js"
Oops, error Error: INTERNAL SERVER ERROR
    at d:\GolandProjects\code-master\demo\fetch.js:23:15
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
Copy the code

Example Change the returned status code of an interface to 400

@app.route('/init', methods=['GET'])
def init() :
    @time: 2022/03/04 19:41:40 @author: Li Ruilong @version: 1.0 @desc: GET request returned JSON ""
    
    data = ["Ajax"."Fetch"."Promise"."Axios"]
    return jsonify(data),400
Copy the code

Error request

[Running] node "d:\GolandProjects\code-master\demo\fetch.js"
INTERNAL SERVER ERROR
Oops, error Error: INTERNAL SERVER ERROR
    at d:\GolandProjects\code-master\demo\fetch.js:24:19
    at processTicksAndRejections (internal/process/task_queues.js:93:5)

[Done] exited with code=0 in 0.261 seconds
Copy the code

Response. ok can also be used directly

// -*- encoding: utf-8 -*-

/* * @file: fetch. Js * @time: 2022/03/04 22:04:04 * @author: Li Ruilong * @version: 1.0 * @contact: [email protected] * @desc: Fetch learning */

const fetch = require("node-fetch");

(async() = > {let url = 'http://127.0.0.1:37881/init';
    try {
        let response = await fetch(url);
        if (response.ok){
            let data = await response.json();
            console.log(data);
            return data;
        }else{
            console.log(response.statusText);
            throw new Error(response.statusText); }}catch (e) {
        console.log("Oops, error", e);
    }
})()
Copy the code

Example Change the returned status code of an interface to 404

@app.route('/init', methods=['GET'])
def init() :
    @time: 2022/03/04 19:41:40 @author: Li Ruilong @version: 1.0 @desc: GET request returned JSON ""
    
    data = ["Ajax"."Fetch"."Promise"."Axios"]
    return jsonify(data),404
Copy the code
[Running] node "d:\GolandProjects\code-master\demo\fetch.js"
NOT FOUND
Oops, error Error: NOT FOUND
    at d:\GolandProjects\code-master\demo\fetch.js:24:19
    at processTicksAndRejections (internal/process/task_queues.js:93:5)

[Done] exited with code=0 in 0.257 seconds
Copy the code

The Response headers attribute

The Response object also has a Response.headers property, which points to a HEADERS object that corresponds to all headers for an HTTP Response.

Headers objects can use for… The of loop iterates.

// -*- encoding: utf-8 -*-

/* * @file: fetch. Js * @time: 2022/03/04 22:04:04 * @author: Li Ruilong * @version: 1.0 * @contact: [email protected] * @desc: Fetch learning */

const fetch = require("node-fetch");

(async() = > {let url = 'http://127.0.0.1:37881/init';
    try {
        let response = await fetch(url);
        if (response.ok){
            let data = await response.json();
            console.log(data);
            for (let [key, value] of response.headers) { 
                //console.log(key+":"+ value);  
                console.log(`${key} : ${value}`);  
              }
            return data;
        }else{
            console.log(response.statusText);
            throw new Error(response.statusText); }}catch (e) {
        console.log("Oops, error", e);
    }
})()
Copy the code
[Running] node "d:\GolandProjects\code-master\demo\fetch.js"
[ 'Ajax'.'Fetch'.'Promise'.'Axios' ]
content-length : 51
content-type : application/json
date : Sat, 05 Mar 2022 15:14:47 GMT
server : Werkzeug/2.0.2 Python/3.9.0

[Done] exited with code=0 in 0.26 seconds
Copy the code

The Headers object provides the following methods to manipulate Headers. In terms of HTTP responses, modifying the header doesn’t make much sense

  • Headers.get(): Returns the key based on the specified key name.
  • Headers.has(): Returns a Boolean value indicating whether a header is included or not.
  • Headers.set(): Sets the specified key name to a new key value, or adds it if it does not already exist.
  • Headers.append(): Adds a header.
  • Headers.delete(): Deletes the header.
  • Headers.keys(): returns a traverser that iterates through all key names in turn.
  • Headers.values(): returns a traverser that traverses all key values in turn.
  • Headers.entries(): Returns a traverser that iterates through all key/value pairs ([key, value]) in turn.
  • Headers.forEach(): Iterates through the headers, executing the argument function once for each header.

Method of reading content

The Response object provides different reading methods depending on the type of data returned by the server. The reads are asynchronous and return Promise objects. You must wait until the asynchronous operation ends to get the complete data returned by the server.

  • response.text(): gets the text string.
  • response.json(): Gets the JSON object.
  • response.blob(): Gets a binary Blob object.
  • response.formData(): Gets the FormData form object.
  • response.arrayBuffer(): Gets a binary ArrayBuffer object.

response.text()Can be used to get text data, for exampleHTMLFile.

@app.route("/")
@app.route("/index")
def default() :
    "@time: 2022/03/04 18:58:42 @author: Li Ruilong @version: 1.0 @desc: Default page"
    return "< h1 > Fetch learning Demo < h1 / >"
Copy the code
// -*- encoding: utf-8 -*-

/* * @file: fetch. Js * @time: 2022/03/04 22:04:04 * @author: Li Ruilong * @version: 1.0 * @contact: [email protected] * @desc: Fetch learning */

const fetch = require("node-fetch");

(async() = > {let url = 'http://127.0.0.1:37881/';
    try {
        let response = await fetch(url);
        if (response.ok){
            let data = await response.text();
            console.log(data);
            return data;
        }else{
            console.log(response.statusText);
            throw new Error(response.statusText); }}catch (e) {
        console.log("Oops, error", e);
    }
})()
Copy the code

response.json() Mainly used to get the return from the server JSONdata

response.formData()It is mainly used in Service workers to intercept forms submitted by users, modify some data, and then submit them to the server.

response.blob()Used to get binary files.

// -*- encoding: utf-8 -*-

/* * @file: fetch. Js * @time: 2022/03/04 22:04:04 * @author: Li Ruilong * @version: 1.0 * @contact: [email protected] * @desc: Fetch learning */

const fetch = require("node-fetch");

(async() = > {let url = 'http://127.0.0.1:37881/download/data.json';
    try {
        let response = await fetch(url);
        if (response.ok){
            let data = await response.blob();
            console.log(data);
            return data;
        }else{
            console.log(response.statusText);
            throw new Error(response.statusText); }}catch (e) {
        console.log("Oops, error", e);
    }
})()
Copy the code
[Running] node "d:\GolandProjects\code-master\demo\fetch.js"
Blob {
  [Symbol(type)]: 'application/json',
  [Symbol(buffer)]: <Buffer 5b 0a 09 7b 0a 09 09 22 73 69 74 65 22 3a 20 22 6e 70 72 22 2c 0a 09 09 22 6c 69 6e 6b 22 3a 20 22 68 74 74 70 3a 2f 2f 77 77 77 2e 6e 70 72 2e 6f 72 ... 141 more bytes>
}

[Done] exited with code=0 in 0.847 seconds
Copy the code

Response.arraybuffer () is mainly used to get streaming media files.

const audioCtx = new window.AudioContext();
const source = audioCtx.createBufferSource();

const response = await fetch('song.ogg');
const buffer = await response.arrayBuffer();

const decodeData = await audioCtx.decodeAudioData(buffer);
source.buffer = buffer;
source.connect(audioCtx.destination);
source.loop = true;
Copy the code

Response.clone()

A Stream object can only be read once, and then it’s gone. This means that only one of the five read methods in the previous section can be used or an error will be reported.

Response object provides response.clone () method to create a copy of Response object and realize multiple reads.

// -*- encoding: utf-8 -*-

/* * @file: fetch. Js * @time: 2022/03/04 22:04:04 * @author: Li Ruilong * @version: 1.0 * @contact: [email protected] * @desc: Fetch learning */

const fetch = require("node-fetch");

(async() = > {let url = 'http://127.0.0.1:37881/download/data.json';
    try {
        let response = await fetch(url);
        let response1 = response.clone();
        if (response.ok){
            let data = await response.json();
            let data1 = await response1.json()
            console.log(data1);
            return data;
        }else{
            console.log(response.statusText);
            throw new Error(response.statusText); }}catch (e) {
        console.log("Oops, error", e);
    }
})()
Copy the code
[Running] node "d:\GolandProjects\code-master\demo\fetch.js"
[
  {
    site: 'npr',
    link: 'http://www.npr.org/rss/rss.php?id=1001'.type: 'rss'
  },
  {
    site: 'npr',
    link: 'http://www.npr.org/rss/rss.php?id=1008'.type: 'rss'
  }
]

[Done] exited with code=0 in 0.25 seconds
Copy the code

Response objects also have a Response.redirect() method, which redirects the Response result to the specified URL. This method is usually only used in Service workers

The Response body attribute

The Response.body property is the underlying interface exposed by the Response object and returns a ReadableStream object for the user to manipulate.

It can be used to read content in chunks, one of which is to show the progress of the download.

// -*- encoding: utf-8 -*-

/* * @file: fetch. Js * @time: 2022/03/04 22:04:04 * @author: Li Ruilong * @version: 1.0 * @contact: [email protected] * @desc: Fetch learning */

const fetch = require("node-fetch");

(async() = > {let url = 'http://127.0.0.1:37881/download/data.json';

    fetch(url)
        .then(response= > response.body)
        .then(res= > res.on('readable'.() = > {
            let chunk;
            while (null! == (chunk = res.read())) {console.log(chunk.toString());
            }
        }))
        .catch(err= > console.log(err)); }) ()Copy the code

The second parameter init: customize the HTTP request

Fetch () takes the URL as its first argument and can also accept a second argument as a configuration object to customize the HTTP request that is made.

HTTP request methods, headers, and data bodies are all set in this object

The Post request passes JSON

@app.route("/add",methods=["POST"])
def add() :
    "@time: 2022/03/04 19:43:05 @author: Li Ruilong @version: 1.0 @desc: Post request"
    data = request.json
    print(*data, sep='\n')
    return jsonify({"msg":"Post request successful"."code":"0"})
Copy the code
// -*- encoding: utf-8 -*-

/* * @file: fetch. Js * @time: 2022/03/04 22:04:04 * @author: Li Ruilong * @version: 1.0 * @contact: [email protected] * @desc: Fetch learning */

const fetch = require("node-fetch");

(async() = > {const url = 'http://127.0.0.1:37881/add';
    const body =  { name:  'John'.surname:  'Smith'  };
    try {
        let response = await fetch(url,{
            method: 'post'.body: JSON.stringify(body),
            headers: {'Content-Type': 'application/json; charset=utf-8'}});if (response.ok){
            const data = await response.json();
            console.log(data);
            return data;
        }else{
            console.log(response.statusText);
            throw new Error(response.statusText); }}catch (e) {
        console.log("Oops, error", e);
    }
})()

Copy the code
[06/Mar/2022 02:27:42]"POST/add HTTP / 1.1" 200 -
========
[Running] node "d:\GolandProjects\code-master\demo\fetch.js"
{ code: '0', msg: 'Post request successful ' }

[Done] exited with code=0 in 0.293 seconds
Copy the code

File upload

@app.route('/upload', methods=['POST'.'PUT'])
def upload() :
    "@time: 2021/12/15 10:32:03 @author: Li Ruilong @version: 1.0 @desc:"
    if request.method == 'POST':
        try:
            f = request.files['file']
            print("Upload file name :===", f.filename)
            basepath = os.path.dirname(__file__)  # Path of the current file
            upload_path = os.path.join(basepath, "\ \".str(f.filename))  
            f.save(upload_path)
            print("Save file path:"+upload_path)
        except Exception as e:
            print("Failed to upload file", e)
    return jsonify({"msg":"Upload file OK"."code":"0"}),200
Copy the code
// -*- encoding: utf-8 -*-

/* * @file: fetch. Js * @time: 2022/03/04 22:04:04 * @author: Li Ruilong * @version: 1.0 * @contact: [email protected] * @desc: Fetch learning */

 const fs = require('fs');
 const fetch = require('node-fetch');
 const FormData = require('form-data');
 let fileStream = fs.readFileSync("./data.json");// Read the file
 let formdata = new FormData();
 const mimetype = 'text/plain'
 formdata.append("file", fileStream, {
    filename: "./data.json".// Upload file name
    contentType: mimetype,// File type identifier
});
(async() = > {const url = 'http://127.0.0.1:37881/upload';
    try {
        let response = await fetch(url,{
            method: 'post'.body: formdata ,
            headers: formdata.getHeaders()
        });
        if (response.ok){
            const data = await response.json();
            console.log(data);
            return data;
        }else{
            console.log(response.statusText);
            throw new Error(response.statusText); }}catch (e) {
        console.log("Oops, error", e);
    }
})()

Copy the code
Json File path: D :\data.json 127.0.0.1 - - [06/Mar/2022 01:37:51]"POST/upload HTTP / 1.1" 200 -
============
[Running] node "d:\GolandProjects\code-master\demo\fetch.js"
{ code: '0', msg: 'Upload file OK' }
Copy the code

Fetch () configures the full API for the object

const response = fetch(url, {
  method: "GET".headers: {
    "Content-Type": "text/plain; charset=UTF-8"
  },
  body: undefined.referrer: "about:client".The referrer attribute is used to set the referer header for the fetch() request.
  referrerPolicy: "no-referrer-when-downgrade".// The referrerPolicy attribute is used to set the rules for the Referer header
  mode: "cors".The mode attribute specifies the mode of the request
  credentials: "same-origin".// The credentials attribute specifies whether cookies are sent.
  cache: "default".// The cache attribute specifies how the cache is handled
  redirect: "follow".// The redirect property specifies how HTTP redirect is handled
  integrity: "".The integrity property specifies a hash value that is used to check whether the data returned by the HTTP response is equal to this preset hash value.
  keepalive: false.The keepalive property is used to tell the browser to hold the connection in the background and continue sending data when the page is unloaded.
  signal: undefined The signal attribute specifies an AbortSignal instance that cancels the fetch() request
});
Copy the code

Cancel the fetch() request

After the fetch() request is sent, if you want to cancel it halfway through, you need to use the AbortController object.

@app.route("/stop/<int:s>")
def stop(s) :
    sleep(s)
    return "OK".200
Copy the code

The request is AbortController and AbortController is AbortController. The fetch() request is AbortController. The signal property of the configuration object must specify that it receives the AbortController instance’s controller.signal.

The Controller.abort () method is used to signal cancellation. Will trigger the abort event at this moment, this event can listen, but can be by the controller. The signal. The aborted attribute to determine whether a cancellation signal has been issued

// -*- encoding: utf-8 -*-

/* * @file: fetch. Js * @time: 2022/03/04 22:04:04 * @author: Li Ruilong * @version: 1.0 * @contact: [email protected] * @desc: Fetch learning */

 const fetch = require('node-fetch');
  //npm install abort-controller
 const AbortController = globalThis.AbortController ||  require('abort-controller')

 const controller = new AbortController();
 const timeout = setTimeout(() = > {
     controller.abort();
 }, 5000);
 
(async() = > {const url = 'http://127.0.0.1:37881/stop/10';
    try {
        const response = await fetch(url, {signal: controller.signal});
        const data = await response.text();
        console.log(data)
    } catch (error) {
            console.log('request was aborted',error);
    } finally {
        clearTimeout(timeout);
    }
})()

Copy the code
[Running] node "d:\GolandProjects\code-master\demo\fetch.js"
request was aborted AbortError: The user aborted a request.
Copy the code

The Node environment

PS D:\GolandProjects\code-master\demo> node -v v12.13.1 PS D:\GolandProjects\code-master\demo> NPM -v 6.12.1ps D:\GolandProjects\code-master\demo> npm init -yCopy the code
{
  "name": "demo"."version": "1.0.0"."description": ""."main": "fetch.js"."dependencies": {
    "abort-controller": "^ 3.0.0"."form-data": "^ 4.0.0"."node-fetch": "^ 2.6.7"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": []."author": ""."license": "ISC"
}
Copy the code

Python environment

PS D:\GolandProjects\code-master> python -V
Python 3.9.0
PS D:\GolandProjects\code-master> pip -V
pip 20.2.3 from d:\python\python310\lib\site-packages\pip (python 3.9)
PS E:\docker> flask --version
Python 3.9.0
Flask 2.0.2
Werkzeug 2.0.2
PS E:\docker>
Copy the code