2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【JavaScript】fetchを使って外部データを取得する

Last updated at Posted at 2020-08-19

1. fetch APIとは

サーバーとデータのやりとりができる機能

(例)
・API経由でサーバーからデータを取得する
 Twitterの場合:タイムラインの取得、ユーザー情報の取得
・API経由でサーバーにデータを送る
 Twitterの場合:新規登録、ログイン情報の送信、ツイート内容の送信

2. fetchメソッドの戻り値は、Promiseオブジェクト

・外部とデータのやりとりを行う場合は、「fetchメソッド」を使う
(fetchメソッドは、非同期処理される)

Trivia API : https://opentdb.com/api_config.php

(例)
const url = "https://opentdb.com/api_config.php";
const p = fetch(url);
console.log(p);
// => 結果:Promise {<pending>}

=> fetchメソッドの戻り値は、Promiseオブジェクト
=> 「Promiseオブジェクト」<= => thenメソッドを経由して、外部データを取得する

3. fetchメソッドの使い方(JSON形式のデータを取得するとき)

使い方
fetch("APIのURL")
	.then(responce => {
		// responce.json()をreturnすることで、次のthenに
		// APIで取得できるデータをオブジェクト形式で渡すことができる
		return responce.json();
	})
	.then(data => {
		// responce.json()で受け取った中身を確認
		// 実際にはここでdataの中身を利用して様々な処理をする
		console.log(data);
	})
(例)
const url = 'https://opentdb.com/api.php?amount=10';

fetch(url)
	.then(res => {
		return res.json();
	})
	.then(data => {
		console.log(data);
	})
// => 結果:{response_code: 0, results: Array(10)}

・thenメソッドを使って、fetchメソッドで取得した実データの受け渡しを行う

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?