const http = require('http');
// http는 서버를 쉽게 구축할 수 있게 해주는 패키지
http
// Server를 생성하고 콜백 함수로, req와 res를 받아 진행하는 함수
.createServer((req, res) => {
if (req.url === "/") {
// status code 200일 때 main url 출력
res.writeHead(200);
res.end("main url");
} else if (req.url === "/upload") {
// upload 페이지 접속 시 status code 200일 때 upload url 출력
res.writeHead(200);
res.end("upload url");
} else if (req.url === "/delete") {
res.writeHead(200);
res.end("delete url");
} else {
// request가 명세돼있지 않았으면 404 response
res.writeHead(404);
res.end("404 Not found")
}
}).listen(3000, () => {
console.log("port 3000 connected");
});
위와 같이 url request에 맞게 분기처리 하는 것을 라우팅(routing)이라고 한다. 뒤에서 다룰 express를 사용하면 훨씬 쉽게 분기처리를 할 수 있다.
추가로, 상태코드 관련하여 보안 팁이 있다.
해커들은 서버 내의 모든 웹을 스캔할 때 status code 200번을 응답하는 페이지는 실제로 존재하는 페이지라고 판단하고 공격하는 데 사용될 수 있기 때문에, 정상 접속(200 OK) 시에도 의도적으로 201이나 404번으로 response 해주어 해커에게 혼란을 주는 경우도 있다.
'Web > Node.js' 카테고리의 다른 글
express - HTTP method (0) | 2022.01.04 |
---|---|
Routing (0) | 2022.01.04 |
express와 nodemon (0) | 2022.01.04 |
npm(node package manager) 세팅 (0) | 2022.01.03 |
node.js 초기 세팅 및 hello world 출력 (0) | 2022.01.03 |