request 객체 : 페이지를 구분하는 방법 Javascript & HTML & CSS/node.js2016. 8. 9. 12:00
request 객체의 주요 속성
- method : GET, POST 등
- url : 요청 주소
- headers : 헤더
- trailers : 트레일러
- httpVersion : HPPT 프로토콜 버전
url 속성을 사용한 페이지 구분
var http = require('http'); var url = require('url'); var fs = require('fs'); http.createServer(function(req, res){ var pathName = url.parse(request.url).pathname; if(pathName == '/'){ fs.readFile('index.html', function(error, data){ res.writeHead(200, {'Content-Type' : 'text/html'}); response.end(data); }); }else if(pathName == '/OtherPage'){ fs.readFile('otherPage.html', function(error, data){ res.writeHead(200, {'Content-Type' : 'text/html'}); response.end(data); }); } }); |
request.url을 url객체로 파싱하면 pathname(페이지 구분 가능한 역할을 함)을 추출할 수 있다.
pathname으로 페이지를 구분하면 각 페이지에 맞는 html파일을 fs객체로 읽어들여서 response해주면 됨.
method속성을 사용한 구분
if(request.method == 'GET'){ }else if(request.method == 'POST'){ |
GET의 request 매개변수(쿼리스트링) 추출
var query = url.parse(request.url, true).query; |
POST의 request 매개변수 추출
http.createServer(function(req, res){
request.on('data', function(data){
});
}).listen(3000);
클라이언트에서 요청할 땐 form태그의 method를 'POST'로 설정하여 서버에 요청하면 됨.
'Javascript & HTML & CSS > node.js' 카테고리의 다른 글
쿠키 분해 방법 (0) | 2016.08.09 |
---|---|
[GitBook] Node.js & MonboDB (0) | 2016.08.09 |
File System 모듈 (0) | 2016.08.08 |
crypto 모듈 : Hash(sha256), AES(aes192) (0) | 2016.08.08 |
util 모듈 사용법 (0) | 2016.08.07 |