지역에 따라 날씨가 검색되게 해보자.
이 전 한 내용을 간단히 살펴보면
1.
OpenWeather api 사이트에서
현재 날씨를 볼 수있는 데이터 API doc을 눌러 들어갔다.
2 .
간단하게 도시 이름을 개발자인 내가 직접 London으로 입력하고서
그 곳 날씨가 뜨게 해보았다.
q에 city name 를 넣고 appid에 회원가입시 받은 키 번호를 넣었다.
3 .
아래와 같이 긴 API url을
좀 더 보기 편하게 나눠보았다.
4 .
html 파일에서 내용을 입력한다.
html 템플릿을 만들고 title에 Weather App
body에 label과 input을 입력한다.
5 .
app.get( ) 메소드 안에 있는 모든 내용을 밖으로 빼고 일단 comment로 바꿔 놓는다.
6.
그리고서 app.get() 안에 html 문서가 보내지도록 한다.
브라우저에 이렇게 나온다.
7.
일단 내용 입력할 수 있는 버튼을 만들고
이 3줄의 코드를 Form 태그로 감싸준다.
action="/"
유저가 submit 버튼을 누르면 입력한 내용이
서버에 있는 "/" (root route)로 가게하고
method="post"
app.post에서 이 form을 사용하게 된다.
8.
일단 post가 잘 작동하는지 확인한다.
9.
유저가 입력한 씨티 이름인 텍스트가 잘 들어왔나 보려면
body-parser가 필요하다.
body-parser는 post request의 body를 살펴볼 수 있게 해주고,
내 input의 name에서 데이터를 가져오게 해주는 패키지이다.
터미널에서 nodemon을 일단 나오고 (control + C) 나서
npm install body-parser 로 다운로드 한다.
body-parser를 다운 받고 나서
다시 nodemon을 실행 시킨다. nodemon app.js
10.
body-parser를 실행 시키고
body-parser를 이용해
app.post()메소드에서
input에 있는 name에서 데이터를 가져온다.
11.
도시 이름 Seoul을 입력하니 콘솔에 Seoul이 나왔다.
12.
comment로 빼놓았던 코드들 모두 post 안으로 집어넣기
맨 마지막 줄에 res.send(); 빠졌음 넣어줘야 함.
13.
const query = "London" 을 입력 받을 수 있게
const query = "req.body.cityName" 으로 바꿔준다.
14.
아래에 있는 문구도 London을 바뀐 시티 네임이 들어올 수 있게 query로 바꿔준다.
15.
결과 확인
벤쿠버를 입력해 보았다.
현재 날씨가 나왔다.
16.
HTML 코드
<!DOCTYPE html>
<html lang="en">
<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 { response } = require("express");
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) {
const query = req.body.cityName;
const units = "metric"
const apiKey = "3db5c76812836cde318eb5d225"
const url = "https://api.openweathermap.org/data/2.5/weather?q=" + query + "&units=" + units + "&appid=" + apiKey;
https.get(url, function(response) {
console.log('statusCode:', response.statusCode);
response.on("data", function(data) {
const weatherData = JSON.parse(data)
const temp = weatherData.main.temp
const weatherDescription = weatherData.weather[0].description
const icon = weatherData.weather[0].icon
const imageUrl = "http://openweathermap.org/img/wn/" + icon + "@2x.png"
res.write("<h1>The temperature in " + query + " is " + temp + " degrees Celcius.</h1>");
res.write("<h3>The weather is currently " + weatherDescription + ". </h3>");
res.write("<img src=" + imageUrl + ">");
res.send();
});
})
});
app.listen(3000, function() {
console.log("Server is running on port 3000.");
});
'Node.js > APIs' 카테고리의 다른 글
뉴스레터앱1] 기본 세팅하기 (0) | 2021.10.10 |
---|---|
날씨 API 불러와서 사이트 만들기 간단 총정리 (0) | 2021.10.09 |
날씨 API에서 날씨에 따라 다른 아이콘 보이게 하기 (0) | 2021.10.08 |
가져온 API 데이터를 유저 브라우저에서 보게하려면? | render하는 법 | express 사용 (0) | 2021.10.08 |
JSON.parse( ) | JSON을 parse 하는 법 (0) | 2021.10.06 |
댓글