環境
- Node: v16.14.2
- wsl2
OpenWeatherのAPIキー取得
- https://openweathermap.org/ でアカウントを取得すると、https://home.openweathermap.org/api_keys でAPI Keyが使えるようになる。
- 今回は、 openweathermap.org を利用する
使用したライブラリ
axios
promise ベースの HTTP クライアント
axios .get(`http://api.openweathermap.org/data/2.5/weather?q=tokyo&units=metric&appid=${API_KEY}&lang=ja`) .then((response) => console.log(response.data)) .catch(console.error)
$ node main.js
で
{ coord: { lon: 139.6917, lat: 35.6895 }, weather: [ { id: 501, main: 'Rain', description: '適度な雨', icon: '10d' } ], base: 'stations', main: { temp: 22.48, feels_like: 22.87, temp_min: 21, temp_max: 24.75, pressure: 1014, humidity: 80 }, visibility: 10000, wind: { speed: 2.57, deg: 330 }, rain: { '1h': 1.47 }, clouds: { all: 75 }, dt: 1663898569, sys: { type: 2, id: 2038398, country: 'JP', sunrise: 1663878567, sunset: 1663922292 }, timezone: 32400, id: 1850144, name: '東京都', cod: 200 }
データが取れた🤗
dotenv
環境変数を.envファイルからロードするモジュール
https://github.com/motdotla/dotenv
request(非推奨)
requestが非推奨だと気づかず、最初に実装したコード。これをaxiosに書き直した。
const resource = { url: `http://api.openweathermap.org/data/2.5/weather?q=tokyo&units=metric&appid=${API_KEY}&lang=ja`, method: "GET", json: true, } request(resource, (error, res, body) => { console.log(body) })
JSONデータの取得
console.log(response.data.name) console.log(response.data['weather'][0]['description']) console.log(response.data.rain['1h'])
でJSONデータを取得できた
東京都 小雨 0.13
ソースコード
GitHub - kei-kmj/weather_app: Node.jsとopenweathreAPIで都市の天気情報を取得するappです。