프로그래밍/Node.js

Node.js - URL별로 다른 HTML 페이지 제공하기

가카리 2015. 1. 2. 13:47
반응형

웹페이지 접속 주소 별로 다른 HTML 페이지를 제공하고 싶다면?

 

만약 naver.com이면 일반 pc 네이버로 접속하고 m.naver.com이면 모바일 네이버로 접속하는 것처럼..

 

request 객체의 url 속성을 이용하여 페이지를 구분할 있습니다.

 

 

Index.html

 

<!DOCTYPE html>

<html>

<head>

       <title>Index</title>

</head>

<body>

       <h1>hello node.js</h1>

</body>

</html>

 

OtherPage.html

 

<!DOCTYPE html>

<html>

<head>

       <title>OtherPage</title>

</head>

<body>

       <h1>hello node.js other page</h1>

</body>

</html>

 

 

Node.js 서버단

server.js

 

//모듈을 추출합니다.

var http = require('http');

var fs = require('fs');

var url = require('url');

 

//서버를 생성 실행합니다.

http.createServer(function(request, response){

       //변수를 선언합니다.

       var pathname = url.parse(request.url).pathname;

      

       //페이지를 구분합니다.

       if(pathname == '/'){

             //Index.html 파일을 읽습니다.

             fs.readFile('./public/Index.html', function(error, data){

                    response.writeHead(200, {'Content-Type': 'text/html'});

                    response.end(data);

             });

      

       }else if(pathname == '/public/OtherPage.html'){

             //OtherPage.html 파일을 읽습니다.

             fs.readFile('./public/OtherPage.html', function(error, data){

                    //응답합니다.

                    response.writeHead(200, {'Content-Type' : 'text/html'});

                    response.end(data);

             });

            

       }else{

      

             console.log(pathname);

       }

      

      

}).listen(52273, function(){

       console.log('Server Running at http://127.0.0.1:52273');

});

 

 

 

결과

 

http://127.0.0.1:52273으로 접속 할 때는 Index.html로 가고

 

http://127.0.0.1:52273/public/OtherPage.html 로 접속하면 OtherPage.html로 간다.

 

 

반응형