Created With

linkFetch

參考資料:fetch() - Web APIs | MDN


Fetch 類似 XMLHttpRequest,但是它提供更強大、更有彈性的功能。

link第一步:向伺服器發出請求 (request)

fetch() 有兩個參數。第一個參數是必要的,就是請求檔案的 URL。第二個參數可有可無,是列出各項設定的物件,以下是一些常用設定,預設值標上*號

實際寫法舉例如下

1linkfetch('http://example.com/data.json')

2link

3linkfetch('http://example.com/data.json', {

4link method: 'POST',

5link headers: {

6link 'Content-Type': 'application/json',

7link },

8link body: JSON.stringify(data)

9link})

上述寫法可以拆解成下述寫法

linkHeaders 和 Request

1link// 自己建立標頭物件,兩種寫法結果相同。

2linkconst myHeaders = new Headers();

3linkmyHeaders.append('Content-Type', 'application/json');

4link

5link// or

6linkconst myHeaders = new Headers({

7link 'Content-Type': 'application/json'

8link});

9link

10link// 自己建立設定物件

11linkconst myInit = {

12link method: 'POST',

13link headers: myHeaders,

14link body: JSON.stringify(data),

15link};

16link

17link// 自己建立請求物件

18linkconst myRequest = new Request('data.json', myInit);

19link

20linkfetch(myRequest)

link第二步:接收伺服器回傳的資料 (response)

.json() 會把回傳的資料轉換成 JSON 物件,換成其他方法就會轉換成其他格式

1link // common function syntax

2link .then(function(response) {

3link return response.json();

4link })

5link

6link // or arrow function syntax

7link .then((response) => response.json())

link第三步:取得回傳的資料 (data)

取得資料後會執行 console.log(),如果要執行自己寫的函式就寫在這裡

1link // common function syntax

2link .then(function(data) {

3link console.log(data);

4link });

5link

6link // or arrow function syntax

7link .then((data) => console.log(data));

link錯誤訊息

如果要顯示錯誤訊息可以這樣寫

1link // common function syntax

2link .then(function(data) {

3link console.log(data);

4link })

5link .catch(function(error) {

6link console.error('有錯誤:', error);

7link });

8link

9link // or arrow function syntax

10link .then((data) => console.log(data))

11link .catch((error) => {

12link console.error('有錯誤:', error);

13link });

link基本寫法

綜合上述三個步驟的最小可行程式碼:

1link// common function syntax

2linkfetch('data.json')

3link .then(function(response) {

4link return response.json();

5link })

6link .then(function(data) {

7link console.log(data);

8link });

9link

10link// or arrow function syntax

11linkfetch('data.json')

12link .then((response) => response.json())

13link .then((data) => console.log(data));

Fetch第一步:向伺服器發出請求 (request)Headers 和 Request第二步:接收伺服器回傳的資料 (response)第三步:取得回傳的資料 (data)錯誤訊息基本寫法

技術筆記

準備chevron_right
HTMLchevron_right
CSS 基礎chevron_right
JS 基礎chevron_right
Git & GitHubchevron_right
CSS 進階chevron_right
Node.jschevron_right

返回個人網站