API 串接的新手探險之旅 -- week 4 hw 1


Posted by estella00911 on 2021-05-05

1 自己嘗試研究 API

先看 JSON Server 的 API 文件

  • npm install -g json-server 安裝 json-server npm 套件。
    結果裝成npm install json-server,就安裝失敗(附註:詳見另一篇,還沒寫好)

  • 之後亂查,還 google 到了 curl -X -GET https://... ,好像是可以用在新增 JSON 資料(curl -X -POST)、取得資料(curl -X -GET )、刪除資料(curl -X -DELETE)。
    好像想起來了,可以用在批次下載指令,以前做報告時,我有用過在下載每一小時的衛星雲圖。我這次嘗試使用curl -X -GET https://... > db.json 下載後,印到 db.json 檔案裡。後來一想,API 串接的概念,就是資料交換,把資料下載下來好像哪裡不太對,因為不正是資料太大或者是想要借用別人的資料,才使用資料交換的概念嗎?如果下載下來,好像不太符合初衷。

  • 又繼續 Google,看到了這個網頁 JSON Server tutorial
    簡直是救星,掃描了一下內容,發現關鍵字get_request.js,還不拿來參考一下,還安裝了 npm 套件的 axios,這次學聰明了,使用 npm install -g axios 就成功安裝。

// get_request.js
const axios = require('axios');

axios.get('http://localhost:3000/users')
    .then(resp => {
        data = resp.data;
        data.forEach(e => {
            console.log(`${e.first_name}, ${e.last_name}, ${e.email}`);
        });
    })
    .catch(error => {
        console.log(error);
    });

然後我就很開心的拿來修改,把 data.forEach(e => {... data = resp.data} 的部分改成我要的迴圈:列出前十本書籍的 id 以及書名,輸出跟 index.js 程式碼如下:

// index.js
const axios = require('axios');
axios.get('https://lidemy-book-store.herokuapp.com/books')
    .then(resp => {
        data = resp.data;
        for (let i=1; i<=10; i++) {
          console.log(data[i].id, data[i].name)
        }
    })
    .catch(error => {
        console.log(error);
    });
# @terminal
$ node index.js # 執行 javascript,輸出前十本書
1 克雷的橋
2 當我想你時,全世界都救不了我
3 我殺的人與殺我的人
4 念念時光真味
5 蜂蜜花火【致年少時光‧限量插畫設計書衣典藏版】
6 苦雨之地
7 你已走遠,我還在練習道別
8 想把餘生的溫柔都給你
9 你是我最熟悉的陌生人
10 偷書賊(25萬本紀念版本)

然後我就抱著喜悅開心的睡覺了,也沒有細查什麼是 axios。結果隔天早上熊熊想到,那到底是什麼套件啊...這麼神奇,而且我也看不懂 then 的意思,這樣交作業好像不太負責任。查了一下 axios 好像跟 vue 有關,又仔細想想,好像還沒學到 vue,所以不能使用,所以我昨天花了半天繞一大圈的找資料,最後又回歸了最原始的方法,就是回去看 [NET101] API串接的實戰影片。

2 回歸原始方法,研究範例

想說如法炮製,試試看 console.log(body) 會印出什麼資料。

// index.js 範例 1
const request = require('request');

request(
  'https://lidemy-book-store.herokuapp.com/books',
  function (error, response, body) {
    console.log('body:',body) // 現在要測試印出的檔案資料長什麼樣
  } 
 )
$ node index.js
[
  {
    "id": 1,
    "name": "克雷的橋"
  },
  {
    "id": 2,
    "name": "當我想你時,全世界都救不了我"
  },
  {
    "id": 3,
    "name": "我殺的人與殺我的人"
  },
  {
    "id": 4,
    "name": "念念時光真味"
  },
  {
    "id": 5,
    "name": "蜂蜜花火【致年少時光‧限量插畫設計書衣典藏版】"
  },
  {
    "id": 6,
    "name": "苦雨之地"
  },
  {
    "id": 7,
    "name": "你已走遠,我還在練習道別"
  },
  {
    "id": 8,
    "name": "想把餘生的溫柔都給你"
  },
  {
    "id": 9,
    "name": "你是我最熟悉的陌生人"
  },
  {
    "id": 10,
    "name": "偷書賊(25萬本紀念版本)"
  },
  {
    "id": 11,
    "name": "在回憶消逝之前"
  },
  {
    "id": 12,
    "name": "懲罰"
  },
  {
    "id": 13,
    "name": "雲邊有個小賣部"
  },
  {
    "id": 14,
    "name": "颶光典籍三部曲:引誓之劍(上下冊套書)"
  },
  {
    "id": 15,
    "name": "危險維納斯"
  },
  {
    "id": 16,
    "name": "大旱"
  },
  {
    "id": 17,
    "name": "最後的再見"
  },
  {
    "id": 18,
    "name": "解憂雜貨店【暢銷35萬冊暖心紀念版】:回饋讀者,一次收藏2款書封!"
  },
  {
    "id": 19,
    "name": "高山上的小郵局:獻給書信和手寫年代的溫暖情詩,2019年最治癒人心的高暖度小說"
  },
  {
    "id": 20,
    "name": "在場證明"
  }
]

結果印出書本目錄,現在我只需要前十本,所以需要使用拿手的迴圈來找出十本書,於是我加了以下迴圈。

const request = require('request');

request(
  'https://lidemy-book-store.herokuapp.com/books' ,
  function (error, response, body) {
    try {
    /* 新增這個迴圈, */
      for (let i=0; i<10; i++) { 
        console.log(body[i].id, body[i].name) 
      }
   /* 新增以上 */
    } catch(error){
      cosole.log(error)
    }
  }  
)

結果印出 undefined。

$ node index.js
undefined undefined
undefined undefined
undefined undefined
undefined undefined
undefined undefined
undefined undefined
undefined undefined
undefined undefined
undefined undefined
undefined undefined

現在就要來看看到底發生什麼事情,console.log(body[i].id, body[i].name) 中變數的表示法是 object 的表示法,但是 body 是什麼型態呢?使用 console.log(typeof(body)) 後發現是 string 的變數型態。就想到 [NET101] 7-3 API 串接實戰的範例 1:DELETE 中的 const json = JSON.parse(body) //JSON 格式的字串 ,看不懂 JSON.parse() MDN 的用法,就去查詢發現: API 文件內的格式是JSON字串,所以我需要把資料從 JSON 格式的字串轉換成 JavaScript 的物件,這樣才能使用 body[i].id 在 js 檔案內擷取資料。
修改 js 檔案,如下:

const request = require('request');

request(
  'https://lidemy-book-store.herokuapp.com/books' ,
  function (error, response, body) {
    /* 新增以下此行:查詢一下資料( body )的資料型態,發現是 string */
    // console.log(typeof(body)) //typeof(body) is string
    try {
    /* 新增以下此行:把 JSON 格式的字串轉換成 JavaScript 的物件 */
      const json = JSON.parse(body) //typeof(json) is object 
      for (let i=0; i<10; i++) {
        console.log(json[i].id, json[i].name)
      }
    } catch(error){
      cosole.log(error)
    }
  }  
)

再輸出一次:

$ node index.js
1 克雷的橋
2 當我想你時,全世界都救不了我
3 我殺的人與殺我的人
4 念念時光真味
5 蜂蜜花火【致年少時光‧限量插畫設計書衣典藏版】
6 苦雨之地
7 你已走遠,我還在練習道別
8 想把餘生的溫柔都給你
9 你是我最熟悉的陌生人
10 偷書賊(25萬本紀念版本)

#API #javascript #beginner







Related Posts

兩週考取AWS Certified Cloud Practitioner:免費資源、準備策略與心得分享

兩週考取AWS Certified Cloud Practitioner:免費資源、準備策略與心得分享

展開運算子(Spread Operator) & 其餘運算子(Rest Operator)

展開運算子(Spread Operator) & 其餘運算子(Rest Operator)

HTML 盒模型 (Box model)

HTML 盒模型 (Box model)


Comments