Hướng dẫn fetch trong javascript
Show Một câu request network bằng fetchfetch('/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 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.typeKhi 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ề
Để khai báo 1 fetch request chỉ
Để 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. 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); }); 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); }); }) 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, { credentials: 'include' }) Nếu muốn gửi credentials khi request URL là cùng nhà*, truyền giá trị 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, { crendentials: 'omit' }) Upload fileSử dụng cùng 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 filevar formData = new FormData(); var photos = document.querySelector("input[type='file'][multiple]"); formData.append('title', 'My Vegas Vacation'); formData.append('photos', photos.files); fetch('https://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:
Xem thêm các việc làm JavaScript hấp dẫn tại TopDev |