在fetch中第一個為請求地址,第二個可以設置請求類型POST,GET,DELETE,UPDATE,PATCH和PUT,隨后可以使用then來接收參數,因為異步操作第一個then標明請求類型,第二個then中可以拿到正確的返回值,catch顯示返回錯誤信息。
fetch('https://XXX', { method: 'POST', body: JSON.stringify({ username: 'admin', password: '*****' }), headers: { 'Content-Type': 'application/json;charset=utf-8' } }).then(response => response.json()).then(data => console.log(data)).catch(err => console.log(err)); fetch("https://api.github.com/users") .then((res) => { return res.json(); console.log(res) }) .then(data => { console.log(data); }) .catch(err => console.log(err));
下載寫法
fetch(url).then(async res => await res.blob()).then(
(blob) => {
console.log(blob);
// 創建隱藏的可下載鏈接
const a = document.createElement('a');
a.style.display = 'none';
a.href = URL.createObjectURL(blob);
// 保存下來的文件名
a.download = filename;
document.body.appendChild(a);
a.click();
// 移除元素
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}
)