[06.03] - HTTP모듈로 웹 서버 만들기 01
1. 서버 만들기
const http = require('http'); //HTTP 내장모듈 가져오기
//req : 요청에 관한 정보, res : 응답에 관한 정보
http.createServer((req, res) => {
//요청이 들어올 때 마다 매번 CALLBACK 함수가 실행된다.
});
- HTTP 모듈을 가져온다.
- 모듈 안에 createServer 함수를 사용해서 서버를 생성한다.
- http는 1요청 1응답이므로 요청이 들어올 때마다 항상 응답하여야 한다.
- 요청이 들어왔을 때 항상 CALLBACK 함수가 실행이 된다.
- 지금은 아무것도 없기 때문에 실행해도 아무런 응답이 없다.
const http = require('http');
const port = 3000;
//http.Server형 객체를 반환받게 된다.
const server = http.createServer((req, res) => {
res.write('<h1>Hello Node</h1>'); //응답
res.end('<p>Hello Server</p>'); //응답을 끝냄, 다시 응답을 들어올 때까지 대기
});
//포트번호와 연결 완료 후 실행될 CALLBACK함수가 인자.
server.listen(port, () => {
//서버에서 실행되는 부분
console.log(`${port}번 포트에서 서버 대기중입니다.`);
});
res.end() => 응답을 종료하는 메서드. 인자가 있다면 그 데이터도 클라이언트로 보내고 종료한다.
res : Http Server Response
클라이언트로 보낼 데이터
https://nodejs.org/dist/latest-v14.x/docs/api/http.html#http_class_http_serverresponse
HTTP | Node.js v14.17.0 Documentation
HTTP# Source Code: lib/http.js To use the HTTP server and client one must require('http'). The HTTP interfaces in Node.js are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly c
nodejs.org
req : http Incoming Message
클라이언트에서 서버로 요청을 보내는 객체
https://nodejs.org/dist/latest-v14.x/docs/api/http.html#http_class_http_incomingmessage
HTTP | Node.js v14.17.0 Documentation
HTTP# Source Code: lib/http.js To use the HTTP server and client one must require('http'). The HTTP interfaces in Node.js are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly c
nodejs.org
const http = require('http');
const port = 8080;
const server = http.createServer((req, res) => {
res.write('<h1>Hello Node</h1>');
res.end('<p>Hello Server!</p>');
});
server.listen(8080);
server.on('listening', () => {
console.log('8080번 포트에서 서버 대기중')
});
server.on('error', (error) => {
console.error(error);
});
Event로도 연결을 수행할 수도 있다.
HTML 파일을 읽어서 서버에서 받아서 출력하기.
server2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Node.js 웹 서버</title>
</head>
<body>
<h1>Node.js 웹 서버</h1>
<p>만들 준비되셨나요</p>
</body>
</html>
server2.js
const fs = require('fs');
const http = require('http');
const port = 8080;
const server = http.createServer((req, res) => {
fs.readFile('./server2.html', (err, data) => {
if(err) throw err;
res.end(data);
})
});
server.listen(port);
server.on('listening', () => {
console.log(`${port}번 포트에서 서버 대기중`);
});
server.on('error', (error) => {
});