response에서 데이터를 가져오는 방법과 실제 JavaScript 객체로 가져온 JSON 데이터를 parse하는 방법, 그리고 그 데이터 중 관심 있는 특정 데이터를 가져오는 방법에 대한 내용
const express = require('express');
const app = express();
const port = 3000;
const https = require('node:https');
app.get("/", (req, res) => {
const url = 'https://api.openweathermap.org/data/2.5/weather?q=Seoul&units=metric&appid={my api key}';
// url에서 응답 받음
https.get(url, (response) => {
// 상태정보 (200: Success / 404: Fail 등)
console.log(response.statusCode);
// response에서 데이터를 가져오는 방법
response.on('data', (data) => {
// 실제 JavaScript 객체로 가져온 JSON 데이터를 parse
const weatherData = JSON.parse(data);
// 그 데이터 중 관심 있는 특정 데이터를 가져오는 방법
const temp = weatherData.main.temp;
const description = weatherData.weather[0].description;
console.log(temp);
console.log(description);
});
});
res.send('Server is up and running.');
});
app.listen(port, () => {
console.log("Server is running on port " + port);
});
참고자료
Udemy - The Complete 2023 Web Development Bootcamp (Dr.Angela Yu)