Hướng dẫn fetch data in javascript - lấy dữ liệu trong javascript

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.

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) })3

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('/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

Hướng dẫn fetch data in javascript - lấy dữ liệu trong javascript

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) })7

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. response.type, với một trong 3 giá trị: basiccorsopaque.

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), 
    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)
      })
    7 sẽ là 
    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)
      })
    9, không có bất kỳ giới hạn việc xem các thông tin trên response.nhà (ứng dụng host trên server A gửi request lên API trên server A), 
    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)
      })
    7 sẽ là 
    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)
      })
    9, 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, 
    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)
      });
    0 trả về sẽ là 
    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)
      });
    1, lúc đó bên trong 
    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)
      });
    2 chúng ta chỉ được phép truy cập đến 
    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)
      });
    3, 
    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)
      });
    4, 
    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)
      });
    5, 
    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)
      });
    6, 
    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)
      });
    7 và 
    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)
      });
    8CORS, nhà em ở Hồ Chí Mình, em quen bạn gái Hà Nội, 
    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)
      });
    0 trả về sẽ là 
    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)
      });
    1, lúc đó bên trong 
    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)
      });
    2 chúng ta chỉ được phép truy cập đến 
    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)
      });
    3, 
    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)
      });
    4, 
    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)
      });
    5, 
    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)
      });
    6, 
    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)
      });
    7 và 
    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)
      });
    8
  • Type 
    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)
      });
    9 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.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ỉ 

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

  • 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: các request nhà kế bên sẽ trả 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);
      });
    2
  • 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);
      });
    3: cho phép nhà khác nếu header trả về cũng là cors
  • 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);
      });
    4 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)
  • 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);
      });
    5 tạo một request không cùng nhà, không trả 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);
      });
    6

Để 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 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.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 Request

Set 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 file

Sử 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 file

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)
  })
0

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