Help us understand the problem. What is going on with this article?

JavaScript: ローカルのJSからfetch APIでGETしたJSONをFileSaver.jsを使ってファイルに保存する

More than 1 year has passed since last update.

ローカルでfetchを使うにはCORS対応が一工夫必要なので、下記の記事を参考までにどうぞ
Qiita - ローカルのHTMLファイルでfetchを試す & CORSとその回避策

やりたいこと

  • ローカルのJSからfetch APIを使って公開APIを叩き、GETしたJSONをファイルに保存する
  • FileSaver.jsというnpmのパッケージをnode.jsとかの無いローカル環境で動かしてみる

FileSaver.js

コード

test.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <script type="text/javascript" src="FileSaver.js"></script>
  </head>
  <body>
    <input type="button" value="取得" onclick="apiRequest()" />
    <div id="export"></div>
    <script>
      async function apiRequest() {
        const downloadUrl =
          "http://zipcloud.ibsnet.co.jp/api/search?zipcode=1620825";
        const response = await fetch(downloadUrl);
        const blob = response.blob();
        const fileName = "test.json";
        saveAs(blob, fileName);
      }
    </script>
  </body>
</html>

ファイルの中身

test.json
{
        "message": null,
    "results": [
        {
            "address1": "東京都",
            "address2": "新宿区",
            "address3": "神楽坂",
            "kana1": "トウキョウト",
            "kana2": "シンジュクク",
            "kana3": "カグラザカ",
            "prefcode": "13",
            "zipcode": "1620825"
        }
    ],
    "status": 200
}

まとめ

  • 簡単だった
  • 今度何やろう
k-shimoji
メンターがほしい
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした