웹 서버가 하는 일은 요청과 응답의 연속이다. 이 때 사용하는 객체가 Response와 Request이다.
Response 객체
writeHead(statusCode, object) : Response 헤더 작성
statusCode는 다음과 같은 의미를 가진다.
1XX : 처리 중
2XX : 성공
3XX : Redirect
4XX : 클라이언트 오류
5XX : 서버 오류
object로는 {'Content-Type' : '[Type]'} 형태의 매개변수를 가진다.
Content-Type은 응답하는 데이터의 형태이다. Content-Type에는 다음과 같은 것을 사용할 수 있다.
text/plain : 기본 텍스트
text/html : html 문서
text/javascript : 자바스크립트 파일
text/css : CSS 문서
text/xml : xml 문서
image/jepg
image/png
video/mpeg
audio/mp3
audio/x-ms-wma
Application/json
Application/x-schockwave-flash : Adboe flash 파일
end([data], [encoding]) : Response 본문 작성
예제
var http = require('http');
var server = http.createServer(funtion(request, response){
response.writeHead(200, {'Content-Type' : 'text/html'});
response.end('<strong>dddddddddddddd</strong>');
});
server.listen(5000, function(){
console.log('Server RRRRRRRRRRRRRRRRRRR');
});
이렇게 하면 html 파일을 통해 보여주게 된다.
다음의 구문을 통해 localhost로 접속했음에도 상태 코드에 의해 강제로 구글로 이동하게 된다.
response.writeHead(302, {'Location' : 'http://www.google.com'});
writeHead()의 두번째 인수에 Set-Cookie를 사용해 쿠키를 생성할 수도 있다.
var http = require('http');
http.createServer(function(request, response){
var date = new Date();
date.setDate(date.getDate() + 7);
response.wrtieHead(200, {
'Content-Type' : 'text/html',
'Set-Cookie' : 'Set-Cookie' : ['Expires =' + date.toUTCString()]
});
response.end('<h1>' + request.headers.cookie + '</h1'>);
}).listen(5000, fucntion() {
console.log('server running');
});
Request 객체
클라이언트의 요청에 대한 정보를 담은 객체.
속성
method : 클라이언트의 요청 방식
url : 클라이언트가 요청한 url
headers : 클라이언트의 요청 메시지 헤더
trailers : 클라이언트의 요청 트레일러
httpVersion : http 프로토콜 버전
예제
localhost 뒤에 '/'로 구분 지은 후 특정 단어를 입력하면 특정 단어로 이름이 지정된 html 파일을 여는 서버.
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function(request, response) {
var urlObj = url.parse(request.url, true);
var filename = urlObj.pathname.replace('/','') + '.html';
fs.readFile(filename, function(err, data){
if(err){
response.writeHead(404, {'Content-Type' : 'text/plain'});
response.end('404 Not Found!! \n');
}
response.writeHead(200, {'Content-Type' : 'text/html'});
response.end(data);
});
}).listen(5000, function(){
console.log('server runngin');
});
'Programming > node.js' 카테고리의 다른 글
express 페이지 라우팅 (0) | 2015.05.12 |
---|---|
express (0) | 2015.05.12 |
http (0) | 2015.05.11 |
비동기 이벤트 프로그래밍, events (0) | 2015.05.11 |
url, querystring (0) | 2015.05.11 |