본문 바로가기
Node.js/APIs

가져온 API 데이터를 유저 브라우저에서 보게하려면? | render하는 법 | express 사용

by CodeMia 2021. 10. 8.

이 앞에서  API에서 받은 데이터를 내 서버로 가져는 것까지 했다.

이제는 이 데이터를 어떻게 클라이언트 브라우저로 전송하는 지 배워보자. 

 

 

 res.send( )  

이 전까지 배운 내용은 다음과 같다.

 

 

 

console.log()로 보는 것을 지우고 

 

가져온 api 데이타를 클라이언트 브라우저로 보내기 위해 

get route안에서 파라미터 res를 써서 res.send()를 사용한다. 

 

콘솔 로그에 담았던 내용을

클라이언트 브라우저로 보내기하고 

아래에 있는 res.send("Server is up and running.")라인은 겹치게 되니 삭제한다. 

 

res.send()는 딱 한 번만 보낼 수 있고,

혹시 2개가 있다면 아래에 있는 코드가 읽히게 된다. 

 

 

 

 

 

클라이언트 브라우저에 날짜 정보를 보내보자. 

문구를 <h1> 태그로 감싸서 문구 글자를 키웠다. 

태그를 앞 뒤로 넣으면 적용이 된다. 

 

res.send( )메소드는 한 번만 쓸 수 있기 때문에 결과적으로 한 문장만 보낼 수 있다. 

여러 문장을 보내야 할 때는 res.write() 메소드를 사용한다. 

마지막엔 res.send()를 넣어준다.

 

 

 

 

 

다음 포스트에서는 날씨 상황에 따라 다른 아이콘 넣는 법을 배워보자. 

 

 


const express = require("express");
const https = require("https");

const app = express();

app.get("/", function(req, res) {
https.get(url, function(response) {

response.on("data", function(data) {
const weatherData = JSON.parse(data);
const temp = weatherData.main.temp
const description = weatherData.weather[0].description;
res.write("<h1>The temperature in London is " + temp + " C.</h1>");
res.write("<h1>The weather is currently " + description + ".</h1>");
res.send();
});
});
})

app.listen(8080, function() {
console.log("server is running on port 8080");
});

 

 

댓글