Created
November 14, 2024 06:50
-
-
Save yukikim/e33b9e876161c9b184e59d479dc06e5f to your computer and use it in GitHub Desktop.
Node[typescript]APIからデータを
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // axios を使う方法 | |
| import axios from 'axios'; | |
| async function fetchData() { | |
| try { | |
| const response = await axios.get('https://api.example.com/data'); | |
| console.log('データ取得成功:', response.data); | |
| } catch (error) { | |
| console.error('データ取得エラー:', error); | |
| } | |
| } | |
| fetchData(); | |
| // node-fetch を使う方法 | |
| // node-fetch をインストール | |
| // npm install node-fetch | |
| import fetch from 'node-fetch'; | |
| async function fetchData() { | |
| try { | |
| const response = await fetch('https://api.example.com/data'); | |
| if (!response.ok) { | |
| throw new Error(`HTTPエラー!ステータス: ${response.status}`); | |
| } | |
| const data = await response.json(); | |
| console.log('データ取得成功:', data); | |
| } catch (error) { | |
| console.error('データ取得エラー:', error); | |
| } | |
| } | |
| fetchData(); | |
| // fetch を使用する(Node.js v18+) | |
| async function fetchData() { | |
| try { | |
| const response = await fetch('https://api.example.com/data'); | |
| if (!response.ok) { | |
| throw new Error(`HTTPエラー!ステータス: ${response.status}`); | |
| } | |
| const data = await response.json(); | |
| console.log('データ取得成功:', data); | |
| } catch (error) { | |
| console.error('データ取得エラー:', error); | |
| } | |
| } | |
| fetchData(); | |
| // エラーハンドリング | |
| /** | |
| API からのレスポンスが 200 番台以外のステータスコードで返された場合や、 | |
| ネットワークエラーが発生した場合のエラーハンドリングを追加することは重要です。 | |
| 上記のコード例では、エラーをキャッチしてログに出力するようにしています。 | |
| **/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment