Examples
fetch(file)
.then(x => x.text())
.then(y => myDisplay(y));
Try it Yourself »
Fetch is based on async and await. The example might be easier to understand like this:
async function getText(file) {
let x = await fetch(file);
let y = await x.text();
myDisplay(y);
}
Try it Yourself »
Use understandable names instead of x and y:
async function getText(file) {
let myObject = await fetch(file);
let myText = await myObject.text();
myDisplay(myText);
}
Try it Yourself »
Definition and Usage
The fetch() method starts the process of fetching a resource from a server.
The fetch() method returns a Promise that resolves to a Response object.
😀 No need for XMLHttpRequest anymore.
Syntax
Parameters
Parameter | Description |
file | Optional. The name of a resource to fetch. |
Return Value
Type | Description |
Promise | A Promise that resolves to a Response object. |
Browser Support
fetch() is an ECMAScript6 (ES6) feature.
ES6 (JavaScript 2015) is supported in all modern browsers:
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
fetch() is not supported in Internet Explorer 11 (or earlier).
Web APIs - Introduction
A Web API is a developer's dream.
- It can extend the functionality of the browser
- It can greatly simplify complex functions
- It can provide easy syntax to complex code
What is Web API?
API stands for Application Programming Interface.
A Web API is an application programming interface for the Web.
A Browser API can extend the functionality of a web browser.
A Server API can extend the functionality of a web server.
Browser APIs
All browsers have a set of built-in Web APIs to support complex operations, and to help accessing data.
For example, the Geolocation API can return the coordinates of where the browser is located.
Example
Get the latitude and longitude of the user's position:
const myElement = document.getElementById("demo");
function getLocation() {
if
(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
myElement.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
myElement.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
Try it Yourself »
Third Party APIs
Third party APIs are not built into your browser.
To use these APIs, you will have to download the code from the Web.
Examples:
- YouTube API - Allows you to display videos on a web site.
- Twitter API - Allows you to display Tweets on a web site.
- Facebook API - Allows you to display Facebook info on a web site.
fetch() cho phép tạo một network request tương tự như XMLHttpRequest(XHR). Sự khác nhau chủ yếu là Fetch hoạt động theo Promises, cho phép viết gọn ràng, dễ nhớ hơn là XHR. API Fetch có trong window.fetch() giờ đã được hỗ trợ phổ biến, bạn không cần polyfill gì đâu, vĩnh biệt IE.
Một câu request network bằng fetch
fetch('/api/some-url') .then( function(response) { if (response.status !== 200) { console.log('Lỗi, mã lỗi ' + response.status); return; } // parse response data response.json().then(data => { console.log(data); }) } ) .catch(err => { console.log('Error :-S', err) });Response của câu fetch() là một đối tượng Stream, nghĩa là khi chúng ta gọi phương thức json(), một Promise được trả về, vì quá trình đọc stream sẽ diễn ra bất đồng bộ.
Bên cạnh các dữ liệu chúng ta có thể truy cập như trong ví dụ trên, chúng ta có thể truy cập đến các meta data khác
fetch('/api/some-url') .then(response => { console.log(response.headers.get('Content-Type')); console.log(response.headers.get('Date')); console.log(response.status); console.log(response.statusText); console.log(response.type); console.log(response.url) })response.type
Khi chúng ta tạo một fetch request, response trả về sẽ chứa response.type, với một trong 3 giá trị: basic, cors, opaque.
Nó cho biết resource này đến từ đâu, cho chúng ta biết cách chúng ta nên đối xử với object trả về
- Nếu request lên cùng một nhà (ứng dụng host trên server A gửi request lên API trên server A), response.type sẽ là basic, không có bất kỳ giới hạn việc xem các thông tin trên response.
- Nếu request dạng CORS, nhà em ở Hồ Chí Mình, em quen bạn gái Hà Nội, type trả về sẽ là cors.cors, lúc đó bên trong header chúng ta chỉ được phép truy cập đến Cache-Control, Content-Language, Content-Type, Expires, Last-Modified và Pragma
- Type opaque cho các request tạo ra khác nhà, và thằng server nó không chấp nhận dạng request CORS, ba má cấm chú quen gái Hà Nội, nghĩa là không trả về dữ liệu, không xem được status của request, chia tay tình yêu.
Để khai báo 1 fetch request chỉ resolve khi thỏa điều kiện mode
- same-origin: các request nhà kế bên sẽ trả về reject
- cors: cho phép nhà khác nếu header trả về cũng là cors
- cors-with-forced-preflight luôn thực hiện kiểm tra preflight. Là trước khi gửi đi, để đảm bảo an toàn, tạo một request dùng phương thức OPTIONS để kiểm tra độ an toàn, (nhà anh có điều kiện ko mà đòi quen bạn gái tận Hà Nội xa xôi)
- no-cors tạo một request không cùng nhà, không trả về CORS
Để khai báo mode
fetch('//some-site.com/cors-enabled/some.json', {mode, 'cors'}) .then(function(response) { return response.text(); }) .then(function(text) { console.log('Request successful', text); }) .catch(function(error) { log('Request failed', error) });Liên kết Promise
Một trong những tính năng hay (và sinh ra rắc rối) của Promise là cho phép mắc-xích-các-Promise lại với nhau.
Khi làm việc với JSON API, chúng ta quan tâm đến status và parse JSON trả về, để đơn giản hóa, đưa phần xử lý kiểm tra status và parse này ra hàm riêng. Chúng ta chỉ lo xử lý kết quả cuối cùng và trường hợp có lỗi
function status(response) { if (response.status >= 200 && response.status < 300) { return Promise.resolve(response) } else { return Promise.reject(new Error(response.statusText)) } } function json(response) { return response.json() } fetch('') .then(status) .then(json) .then(data => { console.log('Request succeeded with JSON response', data); }) .catch(function(error) { console.log('Request failed', error); });POST Request
Set giá trị method và body để tạo một POST request
fetch(url, { method: 'POST', headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" }, body: 'foo=bar&lorem=ipsum' }) .then(json) .then(data => { console.log('Request succeeded with JSON response', data); }) .catch(error => { console.log('Request failed', error); }); })Gửi lên dữ liệu dạng JSON
var data = {username: 'example'}; fetch(url, { method: 'POST', body: JSON.stringify(data), headers:{ 'Content-Type': 'application/json' } }) .then(res => res.json()) .then(response => console.log('Success:', JSON.stringify(response))) .catch(error => console.error('Error:', error))Gửi thông tin xác thực với Fetch
Để gửi kèm thông tin xác thực cookie (user là ai), chúng ta truyền tham số credentials: include
fetch(url, { credentials: 'include' })Nếu muốn gửi credentials khi request URL là cùng nhà*, truyền giá trị same-origin
fetch(url, { crendentials: 'same-origin' })Không choKhông cho trình duyệt gửi thông tin xác thực, dùng omit
fetch(url, { crendentials: 'omit' })Upload file
Sử dụng cùng <input type='file' />, FormData()
var formData = new FormData(); var fileField = document.querySelector("input[type='file']"); formData.append('username', 'abc123'); formData.append('avatar', fileField.files[0]); fetch('//example.com/profile/avatar', { method: 'PUT', body: formData }) .then(response => response.json()) .then(response => console.log('Success:', JSON.stringify(response))); .catch(error => console.error('Error:', error))Upload nhiều file
var formData = new FormData(); var photos = document.querySelector("input[type='file'][multiple]"); formData.append('title', 'My Vegas Vacation'); formData.append('photos', photos.files); fetch('//example.com/posts', { method: 'POST', body: formData }) .then(response => response.json()) .then(response => console.log('Success:', JSON.stringify(response))) .catch(error => console.error('Error:', error));Link bài viết gốc
Có thể bạn quan tâm:
- Axios vs Fetch – 2022 nên sử dụng thằng nào với những tính năng mới trong javascript
- Làm sao để fetch dữ liệu bằng React Hook
- Preload, prefetch và các thuộc tính khác trên link
Xem thêm các việc làm JavaScript hấp dẫn tại TopDev