LoginSignup
2
2

More than 1 year has passed since last update.

【javascript】fetch

Posted at

fetch

サーバー上からデータを取得することができる。

case

取得するデータ形式

  • json
    • オブジェクトのプロパティは""で囲む
    • 要素の最後にカンマをつけない。

[
  {
    "name": "Bob",
    "age": 23
  },
  {
    "name": "Tim",
    "age": 30
  },
  {
    "name": "Sun",
    "age": 25
  }
]


fetch('users.json') //取得先のURLセット
console.log(fetch('users.json'))

  • Promise(すなわちthenが使用できる)とResponseが返却されているのがわかる。

スクリーンショット 2021-11-29 19.04.20.png

  • responseを覗いてみる。
    スクリーンショット 2021-11-29 19.10.00.png

  • prototypeにjsonがある。

  • jsonファイルにアクセスする。

    • thenで階層を深く潜り、jsonファイルにアクセスできた。

fetch('users.json').then(function(response){
    console.log(response)
    return response.json();
}).then(function(json){
    console.log(json)
});

スクリーンショット 2021-11-29 19.13.05.png

  • jsonファイルを加工する。

fetch('users.json').then(function(response){
    console.log(response)
    return response.json();
}).then(function(json){
    console.log(json)
    for(const user of json){
        console.log(`私は${user.name}です。年齢は${user.age}になりました。`)
    }
});

// 私はBobです。年齢は23になりました。
// 私はTimです。年齢は30になりました。
// 私はSunです。年齢は25になりました。


  • await asyncで書いてみる

async function fetchTest(){
    const response = await fetch('users.json'); //awaitでpromiseを受け取る。
    const json = await response.json();
    for(const user of json){
        console.log(`私は${user.name}です。年齢は${user.age}になりました。`);
    }
}

fetchTest();


// 私はBobです。年齢は23になりました。
// 私はTimです。年齢は30になりました。
// 私はSunです。年齢は25になりました。

2
2
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
2