node-fetch使用 vs. async/await ()

node-fetch使用 vs. async/await

Node-fetch 是个很容易使用的网路工具; 让我们能提出 HTTP 的 GET, POST…等的请求, 下载和上传文件。

这篇文章主要是谈关于在使用 async/await 的语法下, node-fetch 常会使用到的场景。

Node-fetch is an easy-to-use web tool; Let’s propose an HTTP GET, POST… and other requests to download and upload files.

This article is mainly about scenarios where node-fetch is commonly used under the syntax of async/await. 

丢出相对应的异常、错误; HTTP 的 3xx/4xx/5xx 状态码:

Throw out the corresponding exceptions and errors; 3xx/4xx/5xx status code for HTTP

     首先, 我们应随时的提醒自己:

  • 当我们提出 HTTP 的请求, 发生了 3xx/4xx/5xx 的 HTTP 状态码, 表示著 HTTP 的请求失败或者是必需要有著额外的步骤来处理著异常。
  • 3xx 的 HTTP 状态码是表示著, 必需要有著额外的步骤来处理著异常。
  • 4xx 的 HTTP 状态码是表示著, 我们所提出 HTTP 的请求是个错误的请求。
  • 5xx 的 HTTP 状态码是表示著, 服务器发生了错误。

First of all, we should always remind ourselves :

  • When we make an HTTP request, an HTTP status code of 3xx/4xx/5xx occurs, indicating HTTP request fails, or additional steps are required to handle the exception.
  • The HTTP status code for 3xx is indicative, and additional steps are required to handle the exception.
  • The HTTP status code for 4xx indicates that the HTTP request we made was terrible.
  • The HTTP status code for 5xx indicates that an error has occurred on the server.

@@@ 当我们只是在 promise-chain 的末端加入 catch(), 是没办法补捉得到由 3xx/4xx/5xx 的 HTTP 状态码所产生的异常或错误的。

因为, 当发生 3xx/4xx/5xx 的 HTTP 状态码时, HTTP 的请求端与服务器端间的通信还是正常运作的; 只是HTTP 的请求端收不到 2xx 的成功状态码。

也就是说, promise-chain 末端的 catch(), 是不会去补捉由 3xx/4xx/5xx 的 HTTP 状态码所产生的异常或错误的; 因为, 当下的请求端与服务器端间的通信还是正常运作的。

所以, 我们必需要自己去写个函式; 能检查、分辨由 HTTP 的服务器端传回到 HTTP 的请求端的 HTTP 的状态码; 2xx/3xx/4xx/5xx; 并且, 当 HTTP 的状态码不是 2xx 时, 能丢出相对应的异常、错误。

@@@ When we add a catch() to the end of the promise chain, there is no way to catch it get by 3xx/4xx/5xx—the HTTP status code of the resulting exception or error.

Because when the HTTP status code of 3xx/4xx/5xx occurs, the communication between the HTTP request side and the server side is usually still working; It’s just that the HTTP requester doesn’t receive a 2xx success status code.

The catch() at the end of the promise chain does not catch exceptions or errors generated by the HTTP status code of 3xx/4xx/5xx; the current communication between the request side and the server side is usually working.

Therefore, we must write a function ourselves; we can check and distinguish the status code of HTTP transmitted back to HTTP request side by the HTTP server;  2xx/3xx/4xx/5xx; Moreover, when the HTTP status code is not 2xx, the corresponding exceptions and errors can be thrown.

代码如下:      

The code is as follows :

async function checkResponseStatus(response) {
    if(response.ok) {
        return response
    } else  {
        throw new Error(`The HTTP status of the response is ${response.status} (${response.statusText})`);
    }
}

我们使用了 Response 物件中的 ok 字段; 当等于 true 时, 表示由 HTTP 的服务器端传回到 HTTP 的请求端的 HTTP 的状态码是 2xx。

这个函式将会在 promise-chain 的起头; 在解析 response body 前; 便会被呼叫到; 以检查、分辨由 HTTP 的服务器端传回到 HTTP 的请求端的 HTTP 的状态码是否是 3xx/4xx/5xx ? 假如是 3xx/4xx/5xx 的 HTTP 的状态码, 函式将会丢出个由我们所定制化的错误。

We used the ok field in the Response object; When equal to true, it represents HTTP from the requester side of HTTP that is passed back to HTTP by the server side of HTTP status code is 2xx.

This function will begin with a promise chain; Before parsing the response body, it will be called; to check whether the status code of HTTP on the requesting side transmitted back to HTTP by the server side of HTTP is 3xx/ 4xx/5xx?  If a 3xx/4xx/5xx HTTP status code, the function will throw an error that we customized.

获取文本或网页

Gets the text or web page

        async/await 简化了 promise 的实现。在 node-fetch 中以 async/await 的方式来实现 HTTP 的异步请求, 将能降低软件开发的复杂度。

        async/await simplifies the implementation of promises. Implementing HTTP asynchronous requests async/await in node-fetch will reduce the complexity of software development.

代码如下: 

The code is as follows:

async function getText(url) {
    try {
        let response = await fetch(url);
        let body = await checkResponseStatus(response);
        return await body.text();
    } catch (err) {
        console.error(err.message);
    }
 } 

getText('https://google.com')
    .then(body => console.log(body))
    .catch(error => console.log(`An error occurred: ${error.message}`));

getText(url); 以 async 标注了它是一个异步的函式。

await fetch(url) 启动了一个 HTTP 的请求到 ‘url’。因为, await 的出现, 使得异步函式; getText(url); 将被暂停, 直到 HTTP 的请求完成; HTTP 的服务器端传回响应 (response) 到 HTTP 的请求端。  

当 HTTP 的请求完成时; HTTP 的服务器端传回响应 (response) 到 HTTP 的请求端; 便呼叫 checkResponseStatus(response); 检查、分辨由HTTP 的服务器端传回到 HTTP 的请求端的 HTTP 的状态码:

  • HTTP 的状态码是 2xx; 回传一个被分解成是文本的 Promise。
  • HTTP 的状态码是 3xx/4xx/5xx; 丢出个由我们所定制化的错误。

getText(url);  Async indicates that it is an asynchronous function.

await fetch(url) starts an HTTP  request to ‘url’. Because the appearance of await makes asynchronous functions, getText(url);  will be paused until the HTTP  request is complete;  The server side of HTTP passes the response back to the requester side of HTTP.  

When the HTTP  request is complete, call checkResponseStatus(response); Check and distinguish the status code of HTTP from the server-side of HTTP to the requester side of HTTP:

  • The status code for HTTP is 2xx; The callback is broken down into a Promise that is text.  
  • The status code for HTTP is 3xx/4xx/5xx; Throw out a mistake that we customized.

获取 JSON

Get the JSON

与获取文本或网页类似的作法。

Similar to getting a text or web page.

代码如下:  

The code is as follows :

async function getJSON(url) {
    try {
        let response = await fetch(url);
        let body = await checkResponseStatus(response);
        return await body.json();
    } catch (err) {
        console.error(err.message);
    }
}  

getJSON('https://jsonplaceholder.typicode.com/users')
    .then(body => {
        console.log("First user in the array:");
        console.log(body[0]);
        console.log(`Name of the first user in the array: ${body[0].name}`);
    })
    .catch(error => console.log(`An error occurred: ${error.message}`));

POST 请求

POST Request

代码如下:   

The code is as follows :

async function postText(url) {
    let todo = {
        userId: 123,
        title: "loren imps-um colors",
        completed: false
    };

    try {
        let response = await fetch(url, {
            method: 'POST',
            body: JSON.stringify(todo),
            headers: {'Content-Type': 'application/json'}
        })
        let body = await checkResponseStatus(response);
        return await body.json();
    } catch (err) {
        console.error(err.message);
    }
}

method: HTTP 请求的方法; 我们使用的是post。

body: HTTP 请求中所包含的 body/data。

headers: headers 中的 Content-Type 表明了 body/data 的数据类型是 JSON。

method: the method of the HTTP request;  We are using post.

body: The body/data contained in the HTTP request.

headers: The Content-Type table in headers states that the data type of body/data is JSON.

 

完整的代码请参考:

For the complete code, please refer to :

https://github.com/KenFang/node-fetch-patterns

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

滚动至顶部