
1. 개요
Node.js에서 http 모듈로 text와 html을 브라우저에서 표시하는 예제이다.
2. 사용법
먼저 http 모듈과 fs 모듈을 선언한다.
var http = require('http');
var fs = require('fs');
아래와 같이 http 객체에 createServer() 함수로 Server를 생성한다.
콜백함수의 파라미터로 request와 response를 받는다.
http.createServer(function(request, response) {
…(중략)…
}).listen(1337, '127.0.0.1');
요청 URL과 method, 그리고 헤더정보를 표시하기 위해 아래와 같이 코드를 작성한다.
headers += "Request URL = " + request.url + "<br>";
headers += "Request type = " + request.method + "<br>";
headers += "Request headers = " + JSON.stringify(request.headers) + "<br>";
요청 URL에 따라 /text와 /html 일때 대상 파일을 읽어서 fileData에 담아두어 화면에 표시한다.
if (request.url == '/text') {
fileData = fs.readFileSync('20-http.txt', 'utf8');
}
if (request.url == '/html') {
fileData = fs.readFileSync('20-http.html', 'utf8');
}
3. 예제
다음은 서버 전체 코드이다.
var http = require('http');
var fs = require('fs');
http.createServer(function(request, response) {
var fileData = "";
var headers = "";
headers += "Request URL = " + request.url + "<br>";
headers += "Request type = " + request.method + "<br>";
headers += "Request headers = " + JSON.stringify(request.headers) + "<br>";
if (request.url == '/text')
{
fileData = fs.readFileSync('20-http.txt', 'utf8');
}
if (request.url == '/html')
{
fileData = fs.readFileSync('20-http.html', 'utf8');
}
response.writeHead(200, { 'Content-Type' : 'text/html; charset=utf-8' });
response.write('<h1>Hello World</h1><br>');
response.write(headers);
response.write('<hr>');
response.end("<br><br>===== fileData =====<br>" + fileData);
}).listen(1337, '127.0.0.1');
console.log('http://127.0.0.1:1337/text');
console.log('http://127.0.0.1:1337/html');
아래는 20-http.txt 파일의 내용입니다. 예전의 네이버 로고이미지를 아스키코드로 변환하였다.

아래는 20-http.html 파일이다.
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
</head>
<body>
<h1>Hello, I'm HTML.</h1>
<h2>Hello, I'm HTML.</h2>
<h3>Hello, I'm HTML.</h3>
<h4>Hello, I'm HTML.</h4>
<h5>Hello, I'm HTML.</h5>
<h6>Hello, I'm HTML.</h6>
</body>
</html>
실행 결과
크롬 브라우저에서 http://127.0.0.1:1337 요청시 아래와 같이 표시된다.

728x90
'■ Front-End ■ > Node.js' 카테고리의 다른 글
[Node.js] http 모듈 - 요청 URL에 따른 다양한 서비스 (0) | 2023.02.26 |
---|---|
[Node.js] http 모듈로 웹으로 GET/POST를 서비스해보자. (0) | 2023.02.26 |
[Node.js] socket.io 모듈을 사용하여 소켓통신을 구현해 보자. (0) | 2023.02.26 |
[Node.js] net 모듈을 사용하여 네트워킹을 해보자. (0) | 2023.02.26 |
[Node.js] fs 모듈을 사용하여 파일을 읽고 쓰기 (0) | 2023.02.26 |
댓글