클라이언트에서 보낸 문자를 대문자 혹은 소문자로 변경하여 다시 클라이언트에게 보내는 간단한 서버를 만들었다.
Express가 아닌 node의 내장모듈인 http를 이용해서 만들었다. 모든 코드는 HTTP 트랜잭션 해부 | Node.js와 HTTP 상태 코드를 참고하여 작성하였다.
const http = require('http');
const PORT = 5000;
const ip = 'localhost';
const server = http.createServer((request, response) => {
let headers = defaultCorsHeader;
let answer = '';
if(request.method === 'POST'){
let body = [];
// 'data'이벤트에서 발생시킨 청크는 Buffer
request.on('data', (chunk) => {
body.push(chunk);
//console.log(body) //[ <Buffer 22 73 64 66 64 66 73 22> ]
}).on('end', () => {
body = Buffer.concat(body).toString();
//console.log(body) //"input"
if(request.url === '/upper'){
answer = body.toUpperCase();
response.writeHead(201, headers);
response.end(JSON.stringify(answer));
}else if(request.url === '/lower'){
answer = body.toLowerCase();
response.writeHead(201, headers);
response.end(JSON.stringify(answer));
}else{
response.writeHead(404, headers);
response.end();
}
})
}
if(request.method === 'OPTIONS'){
response.writeHead(200, headers);
response.end();
}
});
// 요청을 실제로 처리하는 부분
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
};
아래 처럼 사용할 수도 있다!
let data = '';
request.on('data', (chunk) => {
data = data + chunk;
}).on('end', () => {
// data를 활용
}
})
전에 작성했던 TIL로 정리
TIL_20.05.23~24(토,일) - client, server
전에 작성된 클라이언트 코드를 활용하여 채팅 프로그램을 서버를 작성함... 우선 데이터의 저장은 데이터베이스가 아닌 Object에 저장
JSON.parse() -> JSON 문자열의 구문을 분석하고, 그 결과에서 JavaScript 값이나 객체를 생성합니다.
JSON.stringify()-> JavaScript 값이나 객체를 JSON 문자열로 변환
응답헤더 타입설정 등등...
포트 3000번 ip는 로컬 서버를 이용했다.
const http = require("http");
const requestHandler = require('./request-handler');
const port = 3000;
const ip = "127.0.0.1";
const server = http.createServer(requestHandler);
console.log("Listening on http://" + ip + ":" + port);
server.listen(port, ip);
아래는 직접적인 로직이 있는 코드이다. 따로 파일을 분리해서 작성하였다.
const results = {results:[]};
const requestHandler = function(req, res) {
const headers = defaultCorsHeaders;
// 응답하는 컨텐츠의 자료 타입을 헤더에 기록
headers["Content-Type"] = "application/json";
if(req.method === 'OPTIONS'){
res.writeHead(200,headers);
res.end();
}
else if(req.method === 'GET'){
// 저장되어있는 데이터를 보여줌
if (req.url === "/classes/messages") {
const body = JSON.stringify(results);
res.writeHead(200, headers);
res.end(body);
} else if(req.url === '/'){
res.writeHead(200, headers);
res.end('server test');
} else {
res.writeHead(404, headers);
res.end();
}
}
else if(req.method === 'POST'){
if(req.url === '/classes/messages'){
let body = [];
req.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
// body의 type은 string이기 때문에 객체의 형태로 data에 push해줘야 한다.
const data = JSON.parse(body)
results.results.push(data);
res.writeHead(201, headers);
// JSON형태로 바꿔서 응답
res.end(JSON.stringify(data));
});
} else {
res.writeHead(404, headers);
res.end();
}
}
else {
res.writeHead(404, headers);
res.end('404 not found');
}
};
const defaultCorsHeaders = {
"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 // Seconds.
};