### Fetch
FetchAPI提供了一個獲取資源的接口(包括跨域請求),用于訪問和操縱HTTP管道的部分,例如請求和響應。它還提供了一個全局[`fetch()`](https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalFetch/fetch "此頁面仍未被本地化, 期待您的翻譯!")方法,該方法提供了一種簡單,合理的方式來跨網絡異步獲取資源。Fetch API 是基于 Promise 設計,使用了Promises 來處理結果/回調。`fetch()`?必須接受一個參數——資源的路徑。無論請求成功與否,它都返回一個 Promise 對象,resolve 對應請求的?[`Response`](https://developer.mozilla.org/zh-CN/docs/Web/API/Response "Fetch API?的 Response 接口呈現了對一次請求的響應數據。")。你也可以傳一個可選的第二個參數`init`(參見?[`Request`](https://developer.mozilla.org/zh-CN/docs/Web/API/Request "你可以使用? Request.Request() ?構造函數創建一個Request 對象,但是你可能會遇到一個?Request 對象作為其它 API 的操作被返回,比如一個?service worker的FetchEvent.request。"))。
**`Fetch請求`**
```
// fetch('url', '<init對象 可選>')
// **支持請求參數**
fetch('https://www.jianshu.com/users/recommended?seen\_ids=&count=5&only\_unfollowed=true', {test: '測試'})
.then(function(response) {
// 返回一個 JSON Promise,Promise 的解析 resolve 結果是將文本體解析為`JSON`
return response.json()
})
.then(function(data) {
// js格式的json對象
console.log(data)
})
// **指定發送`get`方式**
const fetchRequest = async () => {
let response = await fetch("https://www.jianshu.com/users/recommended?seen\_ids=&count=5&only\_unfollowed=true", {
method: 'get',
})
let data = await response.json()
// js格式的json對象
console.info(data)
}
fetchRequest()
// **上傳JSON數據**
fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers: new Headers({
'Content-Type': 'application/json'
})
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
// **上傳文件**
var formData = new FormData();
var fileField = document.querySelector("input[type='file']");
formData.append('username', '測試');
formData.append('avatar', fileField.files[0]);
fetch('https://example.com/profile/avatar', {
method: 'PUT',
body: formData
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
```
- 版本控制之Git簡介
- Git工作流程
- Git工作區、暫存區、版本庫
- Git 指令匯總
- Git 忽略文件規則 .gitignore
- pull request
- HTTP簡介
- HTTP - Keep-Alive
- HTTP緩存
- XMLHttpRequest
- Fetch
- 跨域
- HTTP 消息頭
- TCP/IP
- TCP首部
- IP首部
- IP 協議
- TCP/IP漫畫
- 前端開發規范
- 前端開發規范整理
- 前端未來規劃
- HTML思維導圖
- CSS思維導圖
- 布局
- position,float,display的關系和優先級
- line-height、height、font-size
- 移動端適配
- JS 對象
- JS 原型模式 - 創建對象
- JS 預編譯
- 探索JS引擎
- ES