fetch
Fetch API 提供了一個 JavaScript接口,用於訪問和操縱HTTP管道的部分,例如請求和響應。它還提供了一個全局 fetch()方法,該方法提供了一種簡單,合理的方式來跨網絡異步獲取資源
- fetch規范與jQuery.ajax()主要有兩種方式的不同:
- 當接收到一個代表錯誤的 HTTP 狀態碼時,從 fetch()返回的 Promise 不會被標記為 reject, 即使該 HTTP 響應的狀態碼是 404 或 500。相反,它會將 Promise 狀態標記為 resolve (但是會將 resolve 的返回值的 ok 屬性設置為 false ),僅當網絡故障時或請求被阻止時,才會標記為 reject。
- 默認情況下,fetch 不會從服務端發送或接收任何 cookies, 如果站點依賴於用戶 session,則會導致未經認證的請求(要發送 cookies,必須設置 credentials 選項)。自從2017年8月25日后,默認的credentials政策變更為same-originFirefox也在61.0b13中改變默認值
進行fetch請求
//fetch( url, config ).then().then().catch() methods: { get () { fetch(`${ BASE_URL }/get.php?a=1&b=2`)//get請求參數是連接在url上 .then( data => data.text() ) .then( res => { this.num = res }) .catch( err => console.log( err )) }, post () { /* 1. post請求參數如何攜帶 */ fetch(`${ BASE_URL }/post.php`,{ method: 'POST', headers: new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式為表單提交 }), body: new URLSearchParams([["a", 1],["b", 2]]).toString() }).then( data => data.text() ) .then( res => { this.sum = res }) .catch( err => console.log( err )) }, getMovies () { /* 第一個then是為數據格式化,可以格式化的數據類型有: json text blob[ 二進制 ] 第二個then才是得到的數據 */ fetch('./mock/movie.json') .then( data => data.json() ) .then( res => { console.log("getMovies -> res", res) this.movies = res.movieList }) } }
- 通過網絡獲取一個JSON文件並將其打印到控制台。最簡單的用法是只提供一個參數用來指明想fetch()到的資源路徑,然后返回一個包含響應結果的promise(一個 Response 對象)。