Tìm nạp nodejs

It is normal in the Javascript setting you need to get data from a URL. Bạn có thể nghĩ đến API XMLHttpRequest, nó thực sự là một API giúp bạn làm được điều bạn muốn, nhưng nó không thân thiện, bạn phải viết mã khá dài để đạt được mục đích. Sử dụng jQuery là một ý tưởng hay, cú pháp jQuery. ajax(. ) ngắn gọn và dễ hiểu, nhưng bạn phải thêm thư viện jQuery vào ứng dụng của mình

ES6 được giới thiệu vào tháng 6 năm 2015, có rất nhiều tính năng mới được đưa vào trong đó có Promise. Và Fetch API là một tiêu chuẩn mới để tạo một yêu cầu (request) gửi đến máy chủ và nhận về một dữ liệu, mục đích của nó giống với XMLHttpRequest, khác biệt là Fetch API được viết dựa trên khái niệm Promise.

Sẽ dễ dàng hơn nếu bạn có khái niệm về Lời hứa trước khi tiếp tục với bài học này, và tôi khuyến nghị bạn tham khảo bài viết dưới đây của tôi, nó hoàn toàn dễ hiểu với tất cả mọi người

API tìm nạp xây dựng một hàm tìm nạp(url,tùy chọn) được sử dụng để lấy dữ liệu từ một URL, hàm này trả về một Lời hứa, nó giống như sau


function fetch(url, options)  {

    // A Promise
    var aPromise = new Promise (
        function (resolve, reject) {

            if (allthingOK) {
               // ...
               var respone = ...;

               resolve(response);
            } else {
                var error = new Error('Error Cause');
                reject(error);
            }

        }
    );

    return aPromise;
}

Và bạn có thể sử dụng API tìm nạp một cách khá đơn giản, chỉ cần gọi hàm tìm nạp(url,tùy chọn) và nhận được lời hứa giải quyết (giải quyết) phản hồi đối tượng


var url = "http://example.com/file";
var options = { method : 'GET', ... };

var aPromise = fetch(url, options);

aPromise
    .then(function(response) {
        
    })
    .catch(function(error) {
        
    });

var aPromise = fetch(url, {
    method: "GET", // POST, PUT, DELETE, etc.
    headers: {
        "Content-Type": "text/plain;charset=UTF-8" // for a string body, depends on body
    },
    body: undefined // string, FormData, Blob, BufferSource, or URLSearchParams
    referrer: "about:client", // "" for no-referrer, or an url from the current origin
    referrerPolicy: "no-referrer-when-downgrade", // no-referrer, origin, same-origin...
    mode: "cors", // same-origin, no-cors
    credentials: "same-origin", // omit, include
    cache: "default", // no-store, reload, no-cache, force-cache, or only-if-cached
    redirect: "follow", // manual, error
    integrity: "", // a hash, like "sha256-abcdef1234567890"
    keepalive: false, // true
    signal: undefined, // AbortController to abort request
    window: window // null
});

2- Nhận văn bản - phản hồi. chữ()

Sử dụng Fetch API để gửi một yêu cầu và nhận về một văn bản là một nhiệm vụ đơn giản và dễ hiểu nhất



This is a simple text data.
 

lấy hàm(. ) trả về một lời hứa giải quyết (giải quyết) một phản hồi đối tượng. Vì vậy để gửi một yêu cầu (request) để lấy về một văn bản dữ liệu bạn cần thực hiện bước 1 như sau

get-text-ví dụ. js (Bước 1)


// A URL returns TEXT data.
var url = "https://ex1.o7planning.com/_testdatas_/simple-text-data.txt";


function doGetTEXT()  {

  // Call fetch(url) with default options.
  // It returns a Promise object (Resolve response object)
  var aPromise = fetch(url);

  // Work with Promise object:
  aPromise
    .then(function(response) {
        console.log("OK! Server returns a response object:");
        console.log(response);
    })
    .catch(function(error)  {
        console.log("Noooooo! Something error:");
        // Network Error!
        console.log(error);
    });

}

Phương thức phản hồi. text() trả về một lời hứa giải quyết một văn bản đối tượng, vì vậy bạn có thể viết tiếp mã cho ví dụ này như sau

get-text-example-way1. js


// A URL returns TEXT data.
var url = "https://ex1.o7planning.com/_testdatas_/simple-text-data.txt";

function doGetTEXT()  {
  // Call fetch(url) with default options.
  // It returns a Promise object (Resolve response object)
  var aPromise = fetch(url);
  // Work with Promise object:
  aPromise
    .then(function(response) {
        console.log("OK! Server returns a response object:");
        console.log(response);
        if(!response.ok)  {
            throw new Error("HTTP error, status = " + response.status);
        }
        response.text()
          .then(function(myText) {
               console.log("Text:");
               console.log(myText);
          })
          .catch(function(error) {
             // Never happened.
          });
    })
    .catch(function(error)  {
        console.log("Noooooo! Something error:");
        // Network Error!
        console.log(error);
    });
}

API tìm nạp được thiết kế để bạn có thể thực hiện các nhiệm vụ theo một dây chuyền (Chuỗi), điều này có thể là do lời hứa phương thức. sau đó(. ), hứa. chụp lấy(. ) cũng được thiết kế để trả lại một lời hứa

Cho dù hàm function(response) mà bạn trả về một giá trị thông thường hay trả về một đối tượng Promise, thì phương thức then() luôn trả về một Promise

Tìm nạp nodejs

get-text-example-way2. js


// A URL returns TEXT data.
var url = "https://ex1.o7planning.com/_testdatas_/simple-text-data.txt";

function doGetTEXT()  {
  // Call fetch(url) with default options.
  // It returns a Promise object (Resolve response object)
  var aPromise = fetch(url);

  // Work with Promise object:
  aPromise
    .then(function(response) {
        console.log("OK! Server returns a response object:");
        console.log(response);
        if(!response.ok)  {
            throw new Error("HTTP error, status = " + response.status);
        }
        return response.text();
    })
    .then(function(myText)  {
         console.log("Text:");
         console.log(myText);
    })
    .catch(function(error)  {
        console.log("Noooooo! Something error:");
        // Network Error!
        console.log(error);
    });
}

get-text-ví dụ. html





    fetch get text
    
    


    

fetch get text

Click the button and see the results in the Console.

3- Nhận JSON - phản hồi. json()

Sử dụng API tìm nạp để gửi một yêu cầu và nhận về một JSON sẽ phức tạp hơn một chút so với việc gửi yêu cầu để nhận về một văn bản. Bởi vì bạn cần xử lý lỗi khi JSON có định dạng không hợp lệ hoặc dữ liệu NULL

json-đơn giản-dữ liệu. json

________số 8

lấy hàm(. ) trả về một lời hứa giải quyết một phản hồi đối tượng

Bước 1 (Step 1), hãy viết mã đơn giản của bạn như sau

get-json-ví dụ. js (Bước 1)


// A URL returns JSON data.
var url = "https://ex1.o7planning.com/_testdatas_/json-simple-data.json";

function doGetJSON()  {
  // Call fetch(url) with default options.
  // It returns a Promise object:
  var aPromise = fetch(url);

  // Work with Promise object:
  aPromise
    .then(function(response) {
        console.log("OK! Server returns a response object:");
        console.log(response);
    })
    .catch(function(error)  {
        console.log("Noooooo! Something error:");
        console.log(error);
    });
}

Cách 1

Phương thức phản hồi. json() đã trả về một lời hứa giải quyết (giải quyết) một đối tượng JSON, vì vậy bạn có thể sử dụng phản hồi theo phương thức. json(). sau đó(. )

get-json-example_way1. js


var url = "http://example.com/file";
var options = { method : 'GET', ... };

var aPromise = fetch(url, options);

aPromise
    .then(function(response) {
        
    })
    .catch(function(error) {
        
    });
0

Cách 2

get-json-example-way2. js


var url = "http://example.com/file";
var options = { method : 'GET', ... };

var aPromise = fetch(url, options);

aPromise
    .then(function(response) {
        
    })
    .catch(function(error) {
        
    });
1

get-json-ví dụ. html


var url = "http://example.com/file";
var options = { method : 'GET', ... };

var aPromise = fetch(url, options);

aPromise
    .then(function(response) {
        
    })
    .catch(function(error) {
        
    });
2

Dữ liệu JSON rỗng?

Chú thích. Phương thức phản hồi. json() có thể ném ra một lỗi, nếu URL của bạn trả về một dữ liệu không phải JSON, hoặc JSON không hợp lệ, hoặc một dữ liệu trống

Giả sử bạn gửi một yêu cầu (request) để lấy thông tin của một thành viên đã nhận theo ID. Trường hợp nhân viên tồn tại tại bạn sẽ nhận được một dữ liệu JSON, đảo ngược nếu nhân viên không tồn tại tại bạn sẽ nhận được một dữ liệu NULL. Tuy nhiên, dữ liệu NULL gây ra lỗi tại vị trí cuộc gọi phản hồi. json(). Please view ví dụ

  • http. //thí dụ. com/employee?id=123

var url = "http://example.com/file";
var options = { method : 'GET', ... };

var aPromise = fetch(url, options);

aPromise
    .then(function(response) {
        
    })
    .catch(function(error) {
        
    });
3

(Lỗi)


var url = "http://example.com/file";
var options = { method : 'GET', ... };

var aPromise = fetch(url, options);

aPromise
    .then(function(response) {
        
    })
    .catch(function(error) {
        
    });
4

Hãy sử dụng phản hồi. text() thay vì phản hồi. json()

get-json-null-ví dụ. js


var url = "http://example.com/file";
var options = { method : 'GET', ... };

var aPromise = fetch(url, options);

aPromise
    .then(function(response) {
        
    })
    .catch(function(error) {
        
    });
5

get-json-null-ví dụ. html


var url = "http://example.com/file";
var options = { method : 'GET', ... };

var aPromise = fetch(url, options);

aPromise
    .then(function(response) {
        
    })
    .catch(function(error) {
        
    });
6

4- Nhận Blob - phản hồi. bãi()

Phương thức phản hồi. blob() trả về một lời hứa giải quyết (giải quyết) một đối tượng Blob

Ví dụ dưới đây tôi sẽ sử dụng Fetch API để tải xuống một ảnh được chọn bởi một URL và hiển thị ảnh đó trên trang

get-blob-ví dụ. js


var url = "http://example.com/file";
var options = { method : 'GET', ... };

var aPromise = fetch(url, options);

aPromise
    .then(function(response) {
        
    })
    .catch(function(error) {
        
    });
7

get-blob-ví dụ. html


var url = "http://example.com/file";
var options = { method : 'GET', ... };

var aPromise = fetch(url, options);

aPromise
    .then(function(response) {
        
    })
    .catch(function(error) {
        
    });
8

5- Nhận ArrayBuffer - phản hồi. mảngBuffer()

Phương thức phản hồi. arrayBuffer() trả về một lời hứa giải quyết (giải quyết) đối tượng ArrayBuffer

Dữ liệu được tải xuống dưới dạng bộ đệm (buffer) giúp bạn có thể làm việc ngay với nó mà không cần phải đợi các đợt toàn bộ dữ liệu được tải về, chẳng hạn một Video có dung lượng lớn, bạn có thể xem Video trong đó

Dưới đây là một ví dụ sử dụng API tìm nạp để phát một tệp nhạc

get-arraybuffer-ví dụ. js


var url = "http://example.com/file";
var options = { method : 'GET', ... };

var aPromise = fetch(url, options);

aPromise
    .then(function(response) {
        
    })
    .catch(function(error) {
        
    });
9

get-arraybuffer-ví dụ. html


var aPromise = fetch(url, {
    method: "GET", // POST, PUT, DELETE, etc.
    headers: {
        "Content-Type": "text/plain;charset=UTF-8" // for a string body, depends on body
    },
    body: undefined // string, FormData, Blob, BufferSource, or URLSearchParams
    referrer: "about:client", // "" for no-referrer, or an url from the current origin
    referrerPolicy: "no-referrer-when-downgrade", // no-referrer, origin, same-origin...
    mode: "cors", // same-origin, no-cors
    credentials: "same-origin", // omit, include
    cache: "default", // no-store, reload, no-cache, force-cache, or only-if-cached
    redirect: "follow", // manual, error
    integrity: "", // a hash, like "sha256-abcdef1234567890"
    keepalive: false, // true
    signal: undefined, // AbortController to abort request
    window: window // null
});
0

Web Audio API giúp bạn có thể làm việc với Audio trên môi trường web, nó là một API lớn và có liên quan đến Fetch API, nếu quan tâm bạn có thể tham khảo bài viết dưới đây

  • Liên kết TODO?

6- Nhận FormData - phản hồi. formData()

Phương thức phản hồi. formData() trả về một lời hứa giải quyết (giải quyết) đối tượng FormData. Bạn thường sử dụng phương thức này tại Service Worker. Khi người dùng gửi Form dữ liệu tới máy chủ, dữ liệu này sẽ đi qua Service Worker trước khi tới máy chủ. Tại Service Worker, bạn có thể gọi phương thức phản hồi. formData(), và sửa đổi các giá trị trong FormData nếu muốn