오늘은 node.js로 server를 구현해보았다.
간단하게 대문자와 소문자 버튼을 누르면 구현되는 페이지다.
클라이언트에는 서버에 자원을 요청하기 위해 fetch와 같이 http요청을 보내는 도구가 기본적으로 내장되어 있다.
node.js에서는 HTTP 요청을 보내거나, 응답 받을 수 있는 도구를 제공하는데, HTTP 요청을 처리하고 응답을 보내주는 프로그램을 웹 서버라고 한다.
const http = require('http');
const PORT = 4999;
const ip = 'localhost';
const server = http.createServer((request, response) => {
if(request.method === 'OPTIONS'){
response.writeHead(200, defaultCorsHeader);
response.end('hello mini-server sprints');}
if(request.method === 'POST' && request.url === '/upper'){
let body = [];
request.on('data', (chunk) => {//chunk는 데이터 조각으로,
//각 data 이벤트에서 발생시킨 청크는 Buffer다.
body.push(chunk);//chunk를 body 배열에 넣는다.
}).on('end', () => {
body = Buffer.concat(body).toString();//이어붙인 후 문자열로 변경
response.writeHead(200, defaultCorsHeader);
response.end(body.toUpperCase());//response객체와 함께 해당 데이터를 보낸다.
});
}
else if(request.method === 'POST' && request.url === '/lower'){
let body = [];
request.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
response.writeHead(200, defaultCorsHeader);
response.end(body.toLowerCase());
});
}else {
//에러
response.statusCode = 404;
response.end();
}
});
node 웹 서버는 createServer로 웹 서버 객체를 만든다.
request-method가 OPTIONS
일 때, 해당 요청은 preflight request
인 경우다.
이 요청을 받을 경우, 서버는 요청 수락 여부를 결정한 뒤에 접근 가능한 조건을 알려주게 되는데, 이를 받고 클라이언트는 서버에 요청을 할 지 결정한다.
POST + end point가 있는 경우
request는 ReadableStream으로 구현하고 있다.
++)stream이란?
일종의 추상적인 개념이다. 프로세스, 파일 등이 어디로 가는지, 어디로 나왔는지 상관없이 통일된 방식으로
데이터를 다루기 위한 가상의 개념이다.
그 중에서 stream들은 읽을수 있거나 = readable
쓸 수 있거나 = writable
둘 다 read & write 될 수 있다.
error 처리
response객체에 statusCode를 담아서 보낸다.
server.listen(PORT, ip, () => {
console.log(`http server listen on ${ip}:${PORT}`);
});
const defaultCorsHeader = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Accept',
'Access-Control-Max-Age': 10
};