brunch

Node.js 기본서버 만들기(2)

by 훈오빵

1. "OK"를 반환하는 서버 만들기

const http = require("http");
const server = http.createServer( (req, res) => {
res.setHeader("Content-Type", "text/html");
res.end("OK");
});

server.listen("3000", () => console.log("OK server started!"));


2. router 만들기

- routing : URL path에 따라 다른 응답을 주는 기능

- URL 형식 : "https://company.com:80/aboutus/#author"

https : 프로토콜 protocol

company.com 호스트명 hostname

:80 포트 port

aboutus 경로 pathname

#author 해시 hash, 일종의 북마크로 서버에 전송하지 않음

const http = require("http");
const url = require("url");
http
.createServer( (req, res) => {
const path = url.parse(req.url, true).pathname;
res.setHeader("Content-Type", "text/html");

if (path === "/user") {
res.end("[user] name : andy, age: 30");
} else if (path === "/feed") {
res.end(`<ul>
<li>picture1</li>
<li>picture2</li>
<li>picture3</li>
</ul>
`);
} else {
res.statusCode = 404;
res.end("404 page not found");
}
}).listen("3000", () => console.log("router is ready!"));


3. createServer() refactoring

- 현재 createServer() 안에서 모든 요청에 대한 응답을 컨트롤 하고 있음. createServer() 안에 모든 콜백 함수에 대한 코드를 추가해야 하므로 좋지 않음. 라우팅 이후의 처리를 별도의 함수를 만들어서 처리하도록 리팩토링 해보기.

const http = require("http");
const url = require("url");
http
.createServer( (req, res) => {
const path = url.parse(req.url, true).pathname;
res.setHeaders("Content-Type", "text/html", "charset=utf-8");

if (path === "/user") {
user(req, res);
} else if (path === "/feed") {
feed(req, res);
} else {
notFound(req, res);
}
})
.listen("3000", () => console.log("router is ready!));

const user = (req, res) => {
res.end(`[user] name : andy, age: 30`);
};

const feed = (req, res) => {
res.end(`<ul>
<li>picture1</li>
<li>picture2</li>
<li>picture3</li>
</ul>
`);
};

const notFound = (req, res) => {
res.statusCode = 404;
res.end("404 Page Not Found");
};


4. 동적으로 응답하기

- user() 함수를 수정해 매개변수에 따라 동적으로 응답하도록 변경

const user = (req, res) => {
const userInfo = url.parse(req.url, true).query;
res.end(`[user] name: ${userInfo.name}, age: ${userInfo.age}`);
};


5. router refactoring

const http = requrie("http");
const url = require("url");

http
.createServer( (req, res) => {
const path = url.parse(req.url, true).pathname;
res.setHeader("Content-Type", "text/html", "charset=utf-8");
if (path in urlMap) {
urlMap[path](req, res);
} else {
notFound(req, res);
}
})
.listen("3000", () => console.log("router refactoring!));

const user = (req, res) => {
res.end(`[user] name : andy, age: 30`);
};

const feed = (req, res) => {
res.end(`<ul>
<li>picture1</li>
<li>picture2</li>
<li>picture3</li>
</ul>
`);
};

const notFound = (req, res) => {
res.statusCode = 404;
res.end("404 Page Not Found");
};

const urlMap = {
"/": (req, res) => res.end("HOME"),
"user": user,
"feed": feed,
};


keyword
매거진의 이전글Node.js 기본서버 만들기(1)