REST
REpresentational State Transfer의 줄임말이며, 서버에 자원을 정의하고 자원에 대한 주소를 지정하는 방법을 가리킵니다.
- GET: 서버 자원을 가져오고자 할 때 사용합니다. 요청의 본문에 데이터를 넣지 않습니다. 데이터를 서버로 보내야 한다면 쿼리스트링을 사용합니다.
- POST: 서버에 자원을 새로 등록하고자 할 때 사용합니다. 요청의 본문에 새로 등록할 데이터를 넣어 보냅니다.
- PUT: 서버의 자원을 요청에 들어 있는 자원으로 치환하고자 할 때 사용합니다. 요청의 본문에 치환할 데이터를 넣어 보냅니다.
- PATCH: 서버 자원의 일부만 수정하고자 할 때 사용합니다. 요청의 본문에 일부 수정할 데이터를 넣어 보냅니다.
- DELETE: 서버의 자원을 삭제하고자 할 때 사용합니다. 요청의 본문에 데이터를 넣지 않습니다.
- OPTIONS: 요청을 하기 전에 통신 옵션을 설명하기 위해 사용합니다.
HTTP 모듈을 사용하여 RESTful한 서버 만들기
const http = require('http');
const fs = require('fs').promises;
const users = {}; // 데이터 저장용
http.createServer(async (req, res) => {
try {
if (req.method === 'GET') {
if (req.url === '/') {
const data = await fs.readFile('./restFront.html');
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
return res.end(data);
} else if (req.url === '/about') {
const data = await fs.readFile('./about.html');
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
return res.end(data);
} else if (req.url === '/users') {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
return res.end(JSON.stringify(users));
}
// /도 /about도 /users도 아니면
try {
const data = await fs.readFile(`.${req.url}`);
return res.end(data);
} catch (err) {
// 주소에 해당하는 라우트를 못 찾았다는 404 Not Found error 발생
}
} else if (req.method === 'POST') {
if (req.url === '/user') {
let body = '';
// 요청의 body를 stream 형식으로 받음
req.on('data', (data) => {
body += data;
});
// 요청의 body를 다 받은 후 실행됨
return req.on('end', () => {
console.log('POST 본문(Body):', body);
const { name } = JSON.parse(body);
const id = Date.now();
users[id] = name;
res.writeHead(201, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('ok');
});
}
} else if (req.method === 'PUT') {
if (req.url.startsWith('/user/')) {
const key = req.url.split('/')[2];
let body = '';
req.on('data', (data) => {
body += data;
});
return req.on('end', () => {
console.log('PUT 본문(Body):', body);
users[key] = JSON.parse(body).name;
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
return res.end('ok');
});
}
} else if (req.method === 'DELETE') {
if (req.url.startsWith('/user/')) {
const key = req.url.split('/')[2];
delete users[key];
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
return res.end('ok');
}
}
res.writeHead(404);
return res.end('NOT FOUND');
} catch (err) {
console.error(err);
res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end(err.message);
}
})
.listen(8082, () => {
console.log('8082번 포트에서 서버 대기 중입니다');
});
front 코드나 관련 코드는 여기를 참조하기 바랍니다.
HTTP 메시지에 관한 자세한 내용은 아래 글을 참조해 주세요.
HTTP 메시지(요청, 응답)
HTTP 요청과 응답 구조는 동일합니다. 요청과 응답은 시작줄(Start Line)과 헤더(Headers)와 바디(Body)로 구성되어 있습니다. 시작줄(Start Line) 모든 Http 메시지는 시작줄(Start Line)으로 시작합니다. 요청..
prefer2.tistory.com
http 모듈만 사용해서 서버를 구성할 수도 있지만, 쿠키, 세션관리가 어려울 뿐만 아니라 주소의 수가 많아지면 코드가 너무 길어지게 됩니다. 다행히도 이를 편리하게 만들어주는 Express 모듈이 있습니다. Express 모듈을 사용하면 미들웨어와 라우터를 사용하여 편리하게 웹 서버를 구성할 수 있습니다.
참조
반응형
'Node.js' 카테고리의 다른 글
[Node.js] node.js 동작 방식: thread & thread pool (0) | 2021.09.29 |
---|---|
[Node.js] Node.js? (0) | 2021.08.24 |