Website with API Data (실시간 도시 날씨)

vancouver·2023년 5월 6일
0

write

 res.write("<h1>The temperature in Seoul is "  + temp +  " degrees Calcius.</h1>")
 res.write("<p>The weather is currently " + description + "<p>")
        res.send();

res.send는 한번밖에 안되서 한문장으로만 가능했지만, write를 쓰면 여러 문장을 표현가능하다.

image 삽입

const icon = weatherData.weather[0].icon
const imgeURL = "https://openweathermap.org/img/wn/" + icon + "@2x.png"
  
res.write("<img src=" + imgeURL + ">") // "<img src= >"

using bodyParser

    <form action="/" method="post">
    <label for="cityInput">City Name: </label>
    <input id ="cityInput" type = "text" name ="cityName">
    <button type = "submit">Go</button>
    </form>

const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended: true}));

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

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

Result

HTML

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weather App</title>
</head>
<body>
    <form action="/" method="post">
    <label for="cityInput">City Name: </label>
    <input id ="cityInput" type = "text" name ="cityName">
    <button type = "submit">Go</button>
    </form>
</body>
</html>

Javascript

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


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

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

app.post("/", function(req,res){
    console.log(req.body.cityName);
    const query = req.body.cityName;
    const apiKey = "84943bd3618afc411e14670414503835";
    const unit = "metric"
    const url = "https://api.openweathermap.org/data/2.5/weather?q=" + query  + "&appid=" + apiKey + "&units=" + unit;
    https.get(url, function(response){
        console.log(response.statusCode);


    response.on("data", function(data){
        const weatherData = JSON.parse(data)
        const description = weatherData.weather[0].description
        const temp = weatherData.main.temp
        const icon = weatherData.weather[0].icon
        const imgeURL = "https://openweathermap.org/img/wn/" + icon + "@2x.png"

        res.write("<h1>The temperature in " + query + " is "  + temp +  " degrees Calcius.</h1>")
        res.write("<p>The weather is currently " + description + "<p>")
        res.write("<img src=" + imgeURL + ">")
    

        })
    })
})

app.listen(3000, function(){
    console.log("Server is running on port 3000")

})


0개의 댓글