LoginSignup
0
0

More than 1 year has passed since last update.

fetchでapi(Json情報)を取得

Last updated at Posted at 2022-02-15

fetchを利用してJson情報を取得します。
Promiseがわかってなくてはまってしまったので、備忘録として残します。

API開発時に役立つJSONPlaceholder - Free Fake REST APIを利用。
何種類かリソースが用意をされておりますが、今回はUSER情報(https://jsonplaceholder.typicode.com/users)
を使用させてもらいます。

JSONPlaceholder

Screenshot(44).png

実装

<h1>fetch</h1>
<h2>名前情報を取得</h2>
<ul id="name_box">
</ul>
let name_box = document.getElementById("name_box");

function getJson(){
    fetch("https://jsonplaceholder.typicode.com/users/")
        .then(response => response.json())
        //response.json()をusersとして扱います
        .then(users => {

        //取得したユーザー情報をイテレートしてhtmlに出力
        for(user of users){
            var list = document.createElement('li');
            list.innerHTML = user.name;
            name_box.appendChild(list);
        }
    });
};

getJson();

結果

Screenshot(45).png

async awaitに書き換えてみよう

実装

<ul id="name_box2">
</ul>
let name_box2 = document.getElementById("name_box2");

async function getJson2(){
    const res2 = await fetch("https://jsonplaceholder.typicode.com/users/");
    //console.log(res2);
    const users2 = await res2.json();
    //console.log(user2);

    //取得したユーザー情報をイテレートしてhtmlに出力
    for (user2 of users2) {
        var list2 = document.createElement('li');
        list2.innerHTML = user2.email;
        name_box2.appendChild(list2);
    }
}

getJson2();

結果

Screenshot(45).png

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