개발 공부/nodejs
[Node.js] http 모듈
짹뚜
2022. 2. 19. 13:47
http 모듈
Node.js에서 웹 서버를 구동시키기 위한 기능들을 제공하는 모듈이다.
const http = require('http');
const server = http.createServer((req, res) => {
res.end('hello world');
});
server.listen(4000, () => {
console.log('Server is Listening...');
});
server
createServer 메서드로 server 객체를 만든다.
- listen(): 서버를 실행시키고 port 번호를 정해준다.
- close(): 서버를 종료한다.
request
createServer의 콜백함수의 첫번째 인자값은 req 또는 request이다. 즉 클라이언트에서 서버로 전달하는 요청 내용을 담고 있는 객체이다.
- method: 클라이언트의 요청 방식이 담겨있다.
- headers: 요청 메시지의 헤더가 담겨있다.
- url: 요청을 한 경로가 담겨있다.
const server = http.createServer((req, res) => {
const { method, headers, url } = req;
console.log('method: ', method);
console.log('headers: ', headers);
console.log('url: ', url);
res.end('hello world');
});
만약 서버로 'GET http://localhost:4000/user' 같은 요청을 보낸다면 각각의 출력 결과는 다음과 같다.
method: GET
headers: { accept: '*/*, host: 'localhost4000', ... }
url: /name
만약 서버로 'POST http://localhost:4000' 요청과 body로는 { data: "hello" }를 보낸다고 하면, 요청의 body 부분은 streamBuffer의 형태로 전송되기 때문에 문자열로 바꾸는 작업이 필요하다. 이 작업에는 on 이벤트를 활용한다.
const server = http.createServer((req, res) => {
let body = [];
if (req.method === 'POST') {
req
.on('data', (chunk) => {
body.push(chunk);
})
.on('end', () => {
body = Buffer.concat(body).toString();
console.log(JSON.parse(body)); // 요청 body가 json 형식이기 때문에 문자열을 json 객체로 변환한다.
});
}
});
response
createServer의 콜백함수의 두번째 인자값은 res, response이다. 서버에서 클라이언트로 보낼 내용을 담고 있는 객체이다.
- writeHead(<status code>, <header>): 응답 메시지의 Status Code와 header를 작성한다.
- write(): 응답 메시지의 body를 작성한다. write()은 여러번 호출할 수 있다.
- end(): 응답 메시지 작성을 종료하고 클라이언트로 전송한다. end()의 인자값으로 body에 들어갈 내용을 작성할 수 있는데, 이 경우에는 인자값을 먼저 body에 작성하고 응답 메시지를 전송한다.
const server = http.createServer((req, res) => {
res.writeHead(200, { 'content-type': 'text/html' });
res.write('<h1>home page<h1>');
res.write('<p>welcome</p>');
res.end();
});