본문 바로가기
Web/Node.js

http module (server, request, response, cookie)

by juein 2018. 3. 2.

http module


[server 객체의 메서드]

createServer() : server객체 생성

listen() : 서버 실행

close() : 서버 종료


//서버 생성 및 종료

//모듈 추출

var http = require('http');
var fs = require('fs');  // <-- html 파일 읽기 용도

var hostname = '호스트 입력';
var port = '포트 입력';

//웹 서버 생성
http.createServer(function(req, res){
    //html 파일 읽기
    fs.readFile('파일명.html', function(err, data){
        res.writeHead(200, {
    		'Content-Type': 'text/html'
    	});
    	res.end(data);
    });
}).listen(port, hostname);

console.log('서버 시작 ://'+hostname+':'+port);

//10초 후 서버 종료
var test = function(){
    server.close();
};

setTimeout(test, 10000);



[response 객체의 메서드]

writeHead() : 응답 헤더

end() : 본문 작성



writeHead()의 'Content-Type'에 따라 이미지, 비디오 파일 등을 제공해 줄수 있다.

'Content-Type' : 'text/plain' // <-- 기본적인 텍스트

'Content-Type' : 'text/html'  // <-- html 파일

'Content-Type' : 'text/xml'   // <-- xml 파일

'Content-Type' : 'image/jpeg' // <-- jpg/jpeg 이미지 파일

'Content-Type' : 'image/png'  // <-- png 이미지 파일

'Content-Type' : 'audio/mp3'  // <-- mp3 파일 등...



[server 객체의 이벤트]

request : 클라이언트가 요청할 때 발생하는 이벤트

connection : 클라이언트가 접속할 때 발생하는 이벤트

close : 서버가 종료될 때 발생하는 이벤트

checkContinue : 클라이언트가 지속적인 연결중일때 발생하는 이벤트

upgrade : 클라이언트가 http 업그레이드를 요청하면 발생하는 이벤트

clientError : 클라이언트에서 오류 발생시 발생하는 이벤트

//server 객체에 이벤트 연결
server.on('request', function(code){
    console.log('이벤트 연결~');
});

server.on('connection', function(){
    console.log('클라이언트가 접속');
});

server.on('close', function(){
    console.log('서버 종료');
});



[request 객체]

request 객체의 속성

method : 클라이언트 요청 방식

url : 클라이언트가 요청한 url

headers : 요청 메시지 헤더

trailers : 요청 메시지 트레일러

httpVersion : http프로토콜 버전



[request 객체의 url 속성을 사용한 페이지 구분]

//url 모듈 추출
var url = require('url');

//서버 생성 및 실행
http.createServer(function(req, res){

    //pathname 변수 선언
    var pathname = url.parse(req.url).pathname;

    //페이지 구분
    if( pathname == '/' ){
        
    }else if( pathname == '/board' ){
        
    }
    
}).listen(port, hostname); 



[request 객체의 method 속성을 사용한 페이지 구분]

//서버 생성 및 실행
http.createServer(function(req, res){

    if( req.method == 'get' ){

        //요청 매게변수 추출
        var query = url.parse(req.url).query;

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

'+ JSON.stringfy(query) +'

'); // <--get 요청 매개변수 값 출력 }else if( req.method == 'post' ){ //post 요청 데이터는 request 이벤트 발생 후 request 객체의 data 이벤트로 전달받는다. req.on('data', function(data){ res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('

'+ data +'

'); // <-- post 요청 값 출력 }); } }).listen(port, hostname);



[쿠키 생성]

response 객체를 사용하여 클라이언트에 쿠키를 할당해주고, request 객체를 사용하여 쿠키를 읽어올 수 있다.

//쿠키 생성 및 쿠키 읽기
http.createServer(function(req, res){

    //get cookie
    var cookie = req.headers.cookie;
    
    //set cookie
	res.writeHead(200, { 
		'Content-Type': 'text/text' ,
        'Set-Cookie' : ['test_cookie = test'] // <-- test_cookie 쿠키생성
	}); 
    
	res.end('

'+ JSON.stringfy(cookie) +'

'); // <-- 쿠키 출력 }).listen(port, hostname);


'Web > Node.js' 카테고리의 다른 글

express moduler  (0) 2018.03.07
express module - request, response 객체  (0) 2018.03.06
Node js Email Send  (0) 2018.03.02
gulp-less  (0) 2018.03.01
Node.js 기본내장모듈  (0) 2018.02.26

댓글