개념
<aside>
🍏 HTTP 를 통해 데이터를 전송할 수 있게 하는 모듈
</aside>
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at <http://$>{hostname}:${port}/`);
});
server 객체
생성 방법
/* Returns: <http.Server> */
const server = http.createServer([options][, requestListener]);
메서드
listen(port[, callback]) |
서버 실행 |
close() |
서버 종료 |
이벤트
request |
클라이언트가 요청할 때 발생하는 이벤트 |
connection |
클라이언트가 접속할 때 발생하는 이벤트 |
close |
서버가 종료될 때 발생하는 이벤트 |
checkContinue |
클라이언트가 지속적인 연결을 하고 있을 때 발생하는 이벤트 |
upgrade |
클라이언트가 HTTP 업그레이드를 요청할 때 발생하는 이벤트 |
clientError |
클라이언트에서 오류가 발생할 때 발생하는 이벤트 |
/* 모듈 추출 */
var http = require('http');
/* server 객체 생성 */
var server = http.createServer();
/* server 객체에 이벤트를 연결 */
server.on('request', function(){
console.log('Request On');
});
server.on('connection', function(){
console.log('Connection On');
});
server.on('close', function(){
console.log('Close On');
});
/* listen() 메서드 실행 */
server.listen(3000);
response 객체
메서드
writeHead(statusCode, object) |
응답 헤더 작성 |
end([data], [encoding]) |
응답 본문 작성 |