Express Framework 기본 이해하기 - server.js

server.js 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const express = require('express');
const app = express();
const PORT = 9900;

app.use(express.static('public'));

app.listen(PORT, () => {
console.log(`Server is listening on http://localhost:${PORT}`);
});

let todos = [
{ id: 3, content: 'JavaScript', completed: false },
{ id: 2, content: 'CSS', completed: true },
{ id: 1, content: 'HTML', completed: false }
];

// 1. FetchTodos
app.get('/todos', (req, res) => {
res.send(todos);
});

// 2. Add todo
app.post('/todos', (req, res) => {
todos = [req.body, ...todos];
res.send(todos);
});

1
2
3
const express = require('express');
const app = express();
const PORT = 9900;

1
2
// The app.use(express.static()) adds a middleware for serving static files to your Express app.
app.use(express.static('public'));

middleware(미들웨어)

Client로부터 request(요청)이 오고
그 request에 대한 response(응답)을 보내는
그 사이에 실행되는 함수이다.
(사진첨부 - 예정)

app.use()

app.use()는 middleware(미들웨어)를 application(app object instance)에 binding한다.

app.use() 안의 함수들은
모두 middleware(미들웨어)이며
request(요청)가 올때마다 이 middleware가 실행된 후,
Client에 response(응답)한다.

express.static(root, [options])

express.static()은 Express의 유일한 기본 제공 middleware(미들웨어) 함수이다.
이 함수는 serve-static을 기반으로 하며, Express application의 정적 자산을 제공한다.

root 인수는 정적 자산의 제공을 시작하는 위치인 root directory를 설정한다.

app.use(express.static(‘public’));

app(=Server)에 request(요청)이 올 때마다
express.static(‘public’)을 실행하여 root directory를 public으로 설정한다.

1
app.use(express.json()); // for parsing application/json

request(요청)에 넘어오는 payload(페이로드)를 json 형식으로 pharsing(파싱)한다.

1
2
3
4
// The app.listen() function is used to bind and listen the connections on the specified host and port.
app.listen(PORT, () => {
console.log(`Server is listening on http://localhost:${PORT}`);
});

app.listen()

app.listen()은 지정된 host 및 port의 connection을 bind(연결)하고 listen(수신 대기)한다.

1
2
3
4
5
6
// Stored data on a server
let todos = [
{ id: 3, content: 'JavaScript', completed: false },
{ id: 2, content: 'CSS', completed: true },
{ id: 1, content: 'HTML', completed: false }
];

서버에 저장된 데이터를 의미한다.

-1. FetchTodos

1
2
3
4
// The app.get() function define a route handler for GET requests to a given URL.
app.get('/todos', (req, res) => {
res.send(todos);
});

app.get(path, handler)

app.get(path, handler)는 주어진 URL로부터 GET request가 올 때 실행될 route handler를 정의한다.

app.get(‘/todos’, (req, res) => { res.send(todos); });

/todos에서 GET requset가 올 경우, response(res)로 todos 데이터를 보낸다.

send() 시,
send framework가 타입을 확인해서 문자열이면 그대로 body에 담아서 보내고,
그 외의 타입이라면 stringify()로 문자열로 바꿔서 보낸다.

-2. Add Todo

1
2
3
4
app.post('/todos', (req, res) => {
todos = [req.body, ...todos];
res.send(todos);
});

/todos에서 POST request가 올 경우, response(res)로 request(req).body를 payload(페이로드)로 보낸다.