Week4 homework


Posted by YongChenSu on 2020-12-08

hw1

  • 要先 npm install request
// 執行後會在 console 列出前十本書籍的 id 以及書名。
const request = require('request')

request(
  'https://lidemy-book-store.herokuapp.com/books',
  function (error, response, body) {
    const BODY = JSON.parse(body)
    for (let i=0; i<10; i++) {
      console.log(BODY[i].id, BODY[i].name)
    }
  }
)

hw2

const request = require('request')
const process = require('process')

const httpMethod = process.argv[2]
const arg = process.argv[3]
const bookNameUpdate = process.argv[4]
const BASE_URL = 'https://lidemy-book-store.herokuapp.com/books'
const originBookArray = [
  {
    name: 'arrayIndex',
  },
  {
    name: '克雷的橋',
  },
  {
    name: '當我想你的時候全世界都救不了我',
  },
  {
    name: '我殺的人與殺我的人',
  },
  {
    name: '念念時光真味',
  },
  {
    name: '我殺的人與殺我的人',
  },
  {
    name: '苦雨之地',
  },
  {
    name: '你已走遠,我還在練習道別',
  },
  {
    name: '想把餘生的溫柔都給你',
  },
  {
    name: '你是我最熟悉的陌生人',
  },
  {
    name: '偷書賊(25萬本紀念版本)',
  },
  {
    name: '在回憶消逝之前',
  },
  {
    name: '懲罰',
  },
  {
    name: '雲邊有個小賣部',
  },
  {
    name: '颶光典籍三部曲:引誓之劍(上下冊套書)',
  },
  {
    name: '危險維納斯',
  },
  {
    name: '大旱',
  },
  {
    name: '最後的再見',
  },
  {
    name: '解憂雜貨店【暢銷35萬冊暖心紀念版】:回饋讀者,一次收藏2款書封!',
  },
  {
    name: '高山上的小郵局:獻給書信和手寫年代的溫暖情詩,2019年最治癒人心的高暖度小說',
  },
  {
    name: '在場證明',
  },
]

switch (httpMethod) {
  case 'list':
    request(BASE_URL, (error, response, body) => console.log(body))
    break
  case 'read':
    request(BASE_URL, (error, response, body) => {
      const BODY = JSON.parse(body)
      console.log(`id: ${BODY[arg - 1].id}`, `name: ${BODY[arg].name}`)
    })
    break
  case 'delete':
    request.delete(`${BASE_URL} / ${arg}`)
    break
  case 'create':
    request.post(
      {
        url: BASE_URL,
        form: {
          name: `${arg}`,
        },
      },
      (error, response, body) => console.log(body),
    )
    break
  case 'update': // 修改原有
    request.patch(
      {
        url: `${BASE_URL} / ${arg}`,
        form: {
          name: `${bookNameUpdate}`,
        },
      },
      (error, response, body) => console.log(body),
    )
    break
  case 'originData': // 將 id 1 ~ 20 的資料復原。
    for (let i = 1; i < 21; i + 1) {
      request.patch(
        {
          url: `${BASE_URL} / ${i}`,
          form: {
            name: originBookArray[i].name,
          },
        },
        (error, response, body) => console.log(body),
      )
    }
    break
  default:
    console.log('Wrong httpMethod')
}

hw3

const request = require('request')
const process = require('process')
const API_ENDPOINT = 'https://restcountries.eu/rest/v2/name/'
const countryName = process.argv[2]

if (!countryName) {
  return console.log('請輸入國家名稱');
}

request(
  API_ENDPOINT + `${countryName}`,
  function(error, response, body) {
    if (error) {
      return console.log('Failure', error)
    }

    const data = JSON.parse(body)

    if (data.status === 404) {
      return console.log('找不到國家資訊')
    }

    for (let i = 0; i < data.length; i++) {
      console.log('============')
      console.log('國家:' + data[i].name)
      console.log('首都:' + data[i].capital)
      console.log('貨幣:' + data[i].currencies[0].code)
      console.log('國碼:' + data[i].callingCodes[0])
    }
  }
)

hw4

前面發 request 時都不是採用最標準的格式寫,這邊就遇到苦頭,反正成功請求,結果就在這一題卡關,雖然不是卡最久的。因還不熟悉,故該寫 method, url, headers 該寫好就得先寫好。

// curl -H 'Accept: application/vnd.twitchtv.v5+json' \
// -H 'Client-ID: 2lqv2fjirubv1wtnirr9a9l68kvub0' \
// -X GET 'https://api.twitch.tv/kraken/games/top' > twitch.html

const request = require('request')
const BASE_URL = 'https://api.twitch.tv/kraken'

request({
    method: 'GET',
    url: `${BASE_URL}/games/top`,
    headers: {
      'Client-ID': '2lqv2fjirubv1wtnirr9a9l68kvub0',
      'Accept': 'application/vnd.twitchtv.v5+json'
    }
  },

  (error, response, body) => {
    const data = JSON.parse(body)
    for (let i=0; i<data.top.length; i++) {
      console.log(
        data.top[i].viewers + ' ' +
        data.top[i].game.localized_name
      )
    }    
  }
)


hw5

1. API 是什麼?

API (Application Programing Interface),應用程式介面

當別人想要跟你要東西時,因不會直接把資料庫的權限給對方,是根據 API (介面) 讓對方可存取資料,也可限制對方資料的存取權限。而當自己想跟對方要資料時也是透過 API。故透過 API 可讓雙方交換資料

2. 說明 3 個課程沒教的 status code?

1. 201 created

通常 POST 或 PUT 之後會回傳 status code: 201,代表請求成功後且建立新的資源

2. 403 forbidden

用戶端並無訪問權限,例如未被授權,所以伺服器拒絕給予應有的回應。不同於 401,伺服端知道用戶端的身份。

3. 505 HTTP Version Not Supported

請求的 HTTP 版本不被伺服器支援。

3. 請提供擁有 CRUD 功能的餐廳 API 文件


API for Restaurant CRUD

BASE_URL:

https://lidemy-restaurant.herokuapp.com

Require authentication:

false

Parameters:

:id

Response:

說明 Method path 參數 範例
獲取所有餐廳 GET /restaurant _limit:限制回傳資料數量 /restaurant?_limit=5
獲取單一餐廳 GET /restaurant/:id /restaurant/10
新增餐廳 POST /restaurant name: 餐廳名
刪除餐通 DELETE /restaurant/:id
更改餐廳資訊 PATCH /restaurant/:id name: 餐廳名

Error code:

205: Invalid parameters

Example Request:

const request = require('request')
const BASE_URL = 'https://lidemy-restaurant.herokuapp.com'

request({
    method: 'GET',
    url: `${BASE_URL}/restaurant/`,
  },

  (error, response, body) => {
    const data = JSON.parse(body)
    console.log(data)
  }
)

Example Response

[
  {
    name: "999'S KITCHEN",
    category: 'Snack',
    foodType: 'Restauration rapide',
    phone: '+687 90.33.33',
    address: '11 RUE ANATOLE FRANCECENTRE VILLE, Centre ville, NOUMEA, Nouvelle-Calédonie',
    city: 'NOUMEA',
    district: 'Centre ville',
    googleMapsUrl: null
  },
  {
    name: 'A LA VIEILLE FRANCE',
    category: 'Boulangerie et boulangerie-pâtisserie',
    foodType: null,
    phone: '+687 27.50.41',
    address: '77 RUE DE SEBASTOPOLQUARTIER LATIN, Quartier latin, NOUMEA, Nouvelle-Calédonie',
    city: 'NOUMEA',
    district: 'Quartier latin',
    googleMapsUrl: 'https://goo.gl/maps/ohTHpEiZCR42'
  },
  {
    name: 'ALIMENTATION CHEZ JASMINE',
    category: 'Alimentation',
    foodType: null,
    phone: '+687 46.28.91',
    address: '24 rue Emile Zola, Mt-Dore, MONT-DORE, Nouvelle-Calédonie',
    city: 'MONT-DORE',
    district: 'Mt-Dore',
    googleMapsUrl: null
  },
]









Related Posts

DAY24:Who likes it?

DAY24:Who likes it?

[ 實作問題 ] Notice: Undefined offset

[ 實作問題 ] Notice: Undefined offset

AI輔導室|快速微調字距與行距

AI輔導室|快速微調字距與行距


Comments