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) })1 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 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) })2 giờ đã được hỗ trợ phổ biến, bạn không cần polyfill gì đâu, vĩnh biệt IE.Promises, cho phép viết gọn ràng, dễ nhớ hơn là XHR. API Fetch có trong 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) })2 giờ đã được hỗ trợ phổ biến, bạn không cần polyfill gì đâu, vĩnh biệt IE. Show
Một câu request network bằng 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) })3fetch('/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('/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) })1 là một đối tượng Stream, nghĩa là khi chúng ta gọi phương thứ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) })5, một 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) })6 được trả về, vì quá trình đọc stream sẽ diễn ra bất đồng bộ.Stream, nghĩa là khi chúng ta gọi phương thứ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) })5, một 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) })6 đượ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) }) 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) })7Khi 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. 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ề
Để khai báo 1 fetch request chỉ 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); });0 khi thỏa điều kiện modemode
Để khai báo mode fetch('http://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 PromiseMộ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.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 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); });7 và 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); });8 JSON trả về, để đơn giản hóa, đưa phần xử lý kiểm tra 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); });7 và 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); });8 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 RequestSet giá trị 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); }); })1 và 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); }); })2 để 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ố 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); }); })3 fetch(url, { credentials: 'include' }) Nếu muốn gửi credentials khi request URL là cùng nhà*, truyền giá trị 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); });1cùng nhà*, truyền giá trị 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); });1 fetch(url, { crendentials: 'same-origin' })Không cho Không cho trình duyệt gửi thông tin xác thực, dùng 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); }); })5 fetch(url, { crendentials: 'omit' }) Upload fileSử dụng cùng 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); }); })6, 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); }); })7 var formData = new FormData(); var fileField = document.querySelector("input[type='file']"); formData.append('username', 'abc123'); formData.append('avatar', fileField.files[0]); fetch('https://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 filefetch('/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) })0 Link bài viết gốc Có thể bạn quan tâm:
Xem thêm các việc làm JavaScript hấp dẫn tại TopDev |