본문 바로가기

Node.js/6. http 웹 모듈

6-1 http 모듈을 이용한 간단한 웹서버


1. http 모듈을 이용하여 index.html 을 로드후 브라우저에 뿌려주는 간단한 서버 프로그램 입니다. 

index.html을 로드 하기 위해 fs 모듈을 이용합니다.  (fs 모듈은  참고하시기 바랍니다.)


server.js 소스 

var fs = require("fs");
var http = require("http");

http.createServer(function(req, res) {
    fs.readFile('index.html', function(err, data){
        res.writeHead(200, {'Content-Type':'text/html'});
        res.end(data);
    });
}).listen(8080, function(){
    console.log("server running");
});


index.html 소스

<!DOCTYPE html>

<html>

    <head>

        <title>Index</title>

    </head>

    <body>

        Hello node.js

    </body>

</html>


로컬에서 실행 하였다면 브라우저로 127.0.0.1:8080 으로 접속합니다. 


- 만일 writeHead 을 지정하지 않으면 일반 파일로 인식하여 해당 파일을 그대로 뿌려줍니다. 위의 예제에선 index.html 을 <!DOCTYPE html> .... </html> 까지 그대로 뿌려줍니다. 




2. 이번엔 페이지별 분기를 만들어 보겠습니다. 만일 url 경로를  / 로 접속한다면 index.html 을 /test 로 접속한다면 test.html 을 보여주는 분기를 만들어 보겠습니다. 

var http = require("http");

http.createServer(function(req, res) {
    console.log(req.url);
}).listen(8080, function(){
    console.log("server running");
});



node server.js 를 실행후 브라우저에 /1 과 /test 로 접속 하면 콘솔창에 아래와 같이 클라이언트가 접속한 url 주소가 나오게 됩니다. 




3. 위의 분기소스를 응용해서 url 에 맞게 html 를 로드 하는 소스 입니다. 

server.js 소스


var fs = require("fs");
var http = require("http");

http.createServer(function(req, res) {
   fs.readFile(__dirname + '/'+ req.url +'.html', function (err, data) {
            res.writeHead(200, { 'Content-Type': 'text/html'});
            res.end(data);
        });
}).listen(8080, function(){
    console.log("server running");
});


test.html 파일 소스


<!DOCTYPE html>

<html>

    <head>

        <title>test.html</title>

    </head>

    <body>

       test

    </body>

</html>



브라우저에서 http://127.0.0.1:8080/index   , http://127.0.0.1:8080/test  로 접속하면 해당 html파일이 로드되서 뿌려지는것을 확인할수 있습니다. 




이처럼 간단하게 html 별로 분기가 가능해집니다. 기본 모듈인 http 만으로도 정말 쉽고 간단하게 서버 프로그래밍이 가능합니다.