반응형
express를 사용하는 이유를 알기 위해
express 없이 서버를 만들어보고, 어떤점이 불편한지 알아보고, express로 서버를 만들어보자
🚀 express없이 서버 만들기
1. 프로젝트 생성
// 프로젝트 폴더 만들고 이동
mkdir node-test
cd node-test
// 프로젝트 시작
npm init -y
// y옵션을 주면 기본값 설정으로 한번에 초기화 할 수 있다.
2. serverWithoutExpress.js 작성
서버로 어떤 요청이 오면 메세지를 보내주도록 작성했다.
// http통신을 하기위해 http모듈을 불러온다
const http = require('http');
// http의 createServer함수로 서버를 만들어서 server변수에 담아줌
const server = http.createServer((req, res) => {
// 요청이 오면 동작.
console.log('request received');
// 응답의 형태가 json이라는 것을 알려줌
res.setHeader('Content-Type', 'application/json');
// 응답으로 보내주는 데이터
res.end(JSON.stringify({ message: "Welcome to server! Http server without express" }));
})
// 서버를 켜는 명령어 listen 8000번 포트에서 켠다.
server.listen(8000, () => (
// 서버가 켜지면 동작
console.log("server is running on PORT 8000")
))
2-1. 여러 api 만들기
요청 url과 메서드에 따라 조건문으로 함수를 분리해서 api를 작성했다.
// http통신을 하기위해 http모듈을 불러온다
const http = require('http');
// sendProducts를 가져와서 쓰기위한 코드. require('sendProducts가있는 파일경로')
const {sendProducts} = require('./sendProducts');
// http의 createServer함수로 서버를 만들어서 server변수에 담아줌
const server = http.createServer((req, res) => {
// url = req.url, method = req.method(구조분해할당)
const {url, method} = req;
// 응답의 형태가 json이라는 것을 알려줌
res.setHeader('Content-Type', 'application/json');
if (url === '/ping'){
return res.end(JSON.stringify({message: "/ pong"}))
}
if (url === '/signup' && method === 'POST') return res.end(JSON.stringify({message: '회원가입 완료!'}))
if (url === '/login' && method === 'POST') return res.end(JSON.stringify({message: '로그인 완료!'}))
if (url === '/products' && method === 'GET')return sendProducts(res)
// 응답으로 보내주는 데이터
res.end(JSON.stringify({ message: 'this response answers to every request' }));
})
// 서버를 켜는 명령어 listen 8000번 포트에서 켠다.
server.listen(8000, () => (
// 서버가 켜지면 동작
console.log("server is running on PORT 8000")
))
더보기
sendProducts.js
const sendProducts = (res) => {
res.end(
JSON.stringify({
products: [{
id: 1,
productName: "node",
description: "node.js is awesome"
}, {
id: 2,
productName: "express",
description: "express is a server-side framework for node.js"
}]
})
)
}
module.exports = { sendProducts } // withoutExpress.js 에서 사용하기 위해 모듈로 내보낸다.
3. 서버실행(터미널)
node serverWithoutExpress.js
실행하면 "server is running on PORT 8000"이 콘솔에 찍히고
브라우저로 localhost:8000에 접속해보면 "request received"가 찍힌다.
express없이 서버를 만들면 불편한점.
- 자바스크립트의 문자열을 프론트엔드에 보내서 통신하기 위해 통신을 위한 문자열 데이터타입인 json형태로 바꿔주는 작업을 해야한다.(JSON.stringify())
- 라우팅을 request객체에서 url과 mothod에 따라 if문으로 분기해서 처리했다.(*라우팅: 해당 자원에 대해 다른 함수(로직)을 실행하도록 하는 것) -> 관리가 힘들다.
이런걸 자동으로 해주기위해 express를 사용한다
🚀 express로 서버 만들기
1. express 설치
npm install express --save
npm으로 express를 설치하면 express와 express를 사용하는 데 필요한 다른 모든 패키지들을 같이 설치해준다.(node_modules폴더에서 확인)
package.json파일에서 내가 받은 패키지 확인 가능
2. serverWithExpress.js작성
const express = require('express')// Express 모듈을 임포트 하고
const app = express() // 함수를 실행해서 app 이란 변수에 담는 것이 컨벤션이다.
// 앱을 사용하는 방법 : app.method('path', handler function)
/*
1. 요청을 받을 http method로 함수를 app 에 붙인다.
2. 요청을 받을 endpoint url 을 string 으로 첫번째 인자에 넣는다.
3. 두번째 인자는 요청과 응답을 인자로 받는 콜백함수이다.
**즉, 각각의 메소드와 엔드포인트에 대해 처리하는(핸들링) 함수가 된다.**
*/
app.get('/ping', (req, res) => {
...
})
// serverWithExpress.js
const http = require('http');
const express = require('express');
const {sendProducts} = require('./sendProducts2');
// express로 앱 생성
const app = express();
// 자바스크립트 객체들을 모두 json으로 변환하라고 미리 알려준다. JSON.stringify()를 쓰지 않아도 되도록.
app.use(express.json());
// express로 만든 앱에 해당 url로 get요청이 들어왔을시 이렇게 동작하겠다
// app.http메서드(url, 콜백함수)
app.get('/ping', (req, res) => {
res.json({message: '/ pong'});
});
app.post('/signup', (req, res) => {res.json({message: '회원가입 완료!'})});
app.post('/login', (req, res) => {res.json({message: '로그인 완료!'})});
app.get('/products', sendProducts);
// 원래는 http.createServer에 모든걸 다 넣어줬는데 위에서 분리를 다 시켜놓고 인자로 app만 준다.
const server = http.createServer(app);
server.listen(8000, () => {
console.log('server is listening on PORT 8000');
})
더보기
sendProducts2.js
const sendProducts = (req, res) => {
res.json({ // 위에서 작성한 sendProducts 함수와 비교했을 때,
// express 덕분에 JSON.stringify 함수를 사용할 필요없이
// response 객체의 json 메소드를 활용.
products: [
{
id: 1,
title: 'node',
description: 'node.js is awesome',
},
{
id: 2,
title: 'express',
description: 'express is a server-side framework for node.js',
},
],
})
}
module.exports = { sendProducts } // routing.js 에서 사용하기 위해 모듈로 내보낸다.
express로 서버를 만드니
- 조건문으로 라우팅을 처리했던 것이 간편해졌고
- 각각의 요청을 처리하는 함수의 분리로 인해 직관적으로 코드를 설계할 수 있게 되었다.
반응형
'TIL' 카테고리의 다른 글
node.js | express로 서버 만들기 - 게시글 등록, 목록조회(DB x) (0) | 2022.09.27 |
---|---|
node.js | express로 서버 만들기 - 회원가입 엔드포인트 만들기(DB x) (0) | 2022.09.26 |
LeetCode | 001. Two Sum (1) | 2022.09.23 |
node.js | express로 서버 띄워보기 (1) | 2022.09.23 |
220714 | Westagram 마무리, 파이썬 함수 key, 리스트[ : ] (0) | 2022.07.15 |