웹페이지 접속 주소 별로 다른 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로 간다.
'프로그래밍 > Node.js' 카테고리의 다른 글
Node.js - req.files이 동작을 안할때 - express (0) | 2015.01.06 |
---|---|
Node.js - response.end 한글 깨짐 현상 해결법 (0) | 2015.01.05 |
Node.js - HTML 페이지에서 입력받고 MYSQL 에 데이터 추가하기 (1) | 2015.01.03 |
Node.js - POST 요청 Node.js에서 처리 방법 (0) | 2015.01.02 |
Node.js - Location 속성을 이용한 페이지 강제 이동 시키기 (0) | 2015.01.02 |
Node.js - 포트2개를 사용한 이미지와 음악파일 서버 만들기 (0) | 2015.01.02 |
Node.js - File System 모듈을 이용한 HTML 페이지 제공 (0) | 2015.01.02 |
Node.js - mysql 데이터베이스 연동 방법 (0) | 2015.01.01 |