이 장에서는 node의 http 모듈로 서버 구축한다.
우리는 마지막 코드를 보며..
Why using the Framework 'express'!!를 느껴야 한다.
노드의 헬로월드 코드 링크: https://nodejs.org/dist/latest-v6.x/docs/api/synopsis.html
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
curl
curl -X GET 'localhost:3000'
const http = require('http');
const hostname = '127.0.0.1';
const port = 3001;
const server = http.createServer((req, res) => {
// 사용자의 요청한 정보의 경로명에 맞게 분기한다.
// req : 사용자의 요청 정보
console.log(req.url);
if (req.url === '/') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n'); // end 함수로 client에게 hello world 보내줌.
} else if (req.url === '/users') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('User list\n'); // end 함수로 client에게 hello world 보내줌.
}
else {
res.statusCode = 404;
res.end('Not Found')
}
});
// listen함수 : 서버를 요청 대기상태로 만들어줌. (서버를 종료시키지 않고 계속 대기중.)
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
node의 http 모듈로 서버 구축 ==> 코드가 길어지고 복잡해 짐에 따라 가독성이 떨어진다.
이로써, FrameWork인 'express'를 사용 할 것이다!!