API - Weather Check Project


Posted by pei_______ on 2022-06-07

Weather Check Project


筆記重點

  1. 使用內建https.get(url, function(response))從外部網址(API)上抓取資料
  2. 使用response.statusCode確認抓取是否成功
  3. 使用JSON.parse(data)將抓取下來的十六進位資料轉換成json檔
  4. 使用res.write()一次傳送多行資料作response

weatherProject.js

const express = require("express")
const bodyParser = require("body-parser")

// 00. set https npm
// don't need to install as it is already in  setted in node
const https = require("https")

const app = express();
app.use(bodyParser.urlencoded({extended: true}));

app.get("/", function(req, res){
  res.sendFile(__dirname + "/index.html")
})

app.post("/", function(req, res){

  const query = req.body.cityName;
  const units = "metric";
  const apiKey = "714acd2036ee335991c2f6554060b8a7";
  const url = "https://api.openweathermap.org/data/2.5/weather?q=" + query + "&units=" + units + "&appid=" + apiKey

  // 01. make request to external web page
  https.get(url, function(response){

    // 02. check whether the requst is success
    console.log(response.statusCode);

    // 03. grab "data" in response (but in hexadecimal)
    response.on("data", function(data){

      // 04. convert into js. object then you can catch data piece
      const weatherData = JSON.parse(data)
      const temp = weatherData.main.temp;
      const weatherDescription = weatherData.weather[0].description;
      const icon = weatherData.weather[0].icon;
      const iconURL = "https://openweathermap.org/img/wn/" + icon + "@2x.png"
      // other function: change js into string by - JSON.stringify(context)

      // 05. Just can send a response.send once in a app
      res.write("<p>The weather is currently " + weatherDescription + ".</p>")
      res.write("<h1>The temperature in " + query + " is " + temp +  " degrees Celcius.</h1>")
      res.write("<img src="+iconURL+">")
      res.send()
    })
  })
})

app.listen(3000, function(){
  console.log("server is running")
})

index.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Weather </title>
  </head>
  <body>
    <form  action="/" method="post">
      <label for="cityInput">City name: </label>
      <input id="cityInput" type="text" name="cityName">
      <button type="submit">send</button>
    </form>
  </body>
</html>

#node.js #Express #web系列







Related Posts

Print a Christmas tree in JavaScript

Print a Christmas tree in JavaScript

第七週報名表單檢討

第七週報名表單檢討

變數及規則、Undefined、Null、NaN差異?

變數及規則、Undefined、Null、NaN差異?


Comments