먼저 시작하기 전에 node.js는 server가 아니다. node.js 공식문서에 어디에도 node.js가 server라는 말은 없다.
node.js는 chrome v8 javascript 엔진으로 빌드된 javascript 런타임이다.
javascript 런타임이란? javascript 언어가 구동되는 환경이다. runtime은 프로그래밍 언어가 구동되는 환경을 뜻하는데
javascript runtime이라고 하면 node.js나 크롬 브라우저 등을 말할 수 있다. (javascript 언어가 구동되는 환경)
그럼 이제 node로 서버를 구동해보자.
1. node 설치
2. back 폴더 안에서 git init
$git init
3. back/app.js
const http = require('http'); // http는 통신 규약으로 node에 내장 되어있다.
const server = http.createServer((req, res) => {
console.log(req.url, req.method);
res.end('hello http');
});
server.listen(3065, () => {
console.log('서버 실행중');
});
$node app.js
서버를 실행해주면 "서버 실행중" 이라는 문구가 뜬다.
http로 server를 구성해도 되지만 불편한점이 있다. 요청 시 마다 조건문이 많이 들어가게 되고 코드가 지저분해진다는 것이다.
아래의 예를 살펴보자.
const http = require('http'); // http는 통신 규약으로 node에 내장 되어있다.
const server = http.createServer((req, res) => {
console.log(req.url, req.method);
if(req.method === 'GET') {
if(req.url === './api/post'){
// todo
}
}
if(req.method === 'POST') {
if(req.url === './api/post'){
// todo
}
}
if(req.method === 'DELETE') {
if(req.url === './api/post'){
// todo
}
}
});
server.listen(3065, () => {
console.log('서버 실행중');
});
이렇게 조건문이 많아지면 코드가 지저분에지고 직관적으로 보는데 다소 어려움이 있다. 때문에 express라는 프레임워크를 통해
보다 직관적이고 구조적으로 서버를 구성할 수 있도록 할 것이다.
'node.js' 카테고리의 다른 글
sequelize model 만들기 (0) | 2022.01.16 |
---|---|
MySQL과 sequelize 연결하기 (0) | 2022.01.16 |
express 라우터 분리하기 (0) | 2022.01.16 |
서버 자동실행을 위한 nodemon (0) | 2022.01.16 |
express로 라우팅하기 (0) | 2022.01.16 |