자바 공부/[자바] 기본 공부

[Node.js 2일차] http 모듈

햅2024 2024. 11. 28. 20:45

2. http 모듈

  • HTTP Protocol을 구현할 수 있는 Node.js의 가장 기본적인 웹 모듈
  • HTTP Web Server 및 Client를 생성하는 모든 기능 담당
  • 보유 객체 
    • Server
    • Response
    • Request
  • 장점 : 빠른 메세징 처리

 

//Create Server

 

var http = require("http");
var fs = require("fs");
var url = require("url");

//Create Server
http.createServer(function(request, response){
    console.log("Web Server Created");
    console.log(request);
}).listen(10002);

 

cmd 창 -> node server.js 입력

chorme 창 -> localhost:10002 접속

 

서버 종료 방법 (컨트롤+C -> cls 입력)

 

//포트네임을 제외한 주소 http://localhost:10002/login 시, /login 이 나옴

var pathName = url.parse(request.url).pathname; 
console.log("pathname : " + pathName);

 

//Root 접속 시 index.html로 세팅

if(pathName == "/"){
    pathName = "/index.html";
}

 

//Read File

1) 에러 발생 -> 없는 파일을 읽을 경우

fs.readFile(pathName.substr(1), function(err, data){
    if(err){
        console.log(err);
        //Page Not Found(404) return
        response.writeHead(404, {'Content-Type' : 'text/html'});
    }
});

 

2)에러가 없을 경우

else{
    //페이지를 찾았음
    response.writeHead(200, {'Content-Type': 'text/html'});
    
     //파일을 읽어 Body에 기술
    response.write(data.toString());
}

 

 

server.js

var http = require("http");
var fs = require("fs");
var url = require("url");

//Create Server
http.createServer(function(request, response){
    console.log("Web Server Created");
    console.log(request.url); 

    //URL 뒤에 있는 디렉토리/파일명 해석
    var pathName = url.parse(request.url).pathname; //포트네임을 제외한 주소 http://localhost:10002/login 시, /login 이 나옴

    console.log("pathname : " + pathName);

    //Root 접속 시 index.html로 세팅
    if(pathName == "/"){
        pathName = "/index.html";
    }

    //Read File
    fs.readFile(pathName.substr(1), function(err, data){
        if(err){
            console.log(err);
            //Page Not Found(404) return
            response.writeHead(404, {'Content-Type' : 'text/html'});
        }
        else{
            //페이지를 찾았음
            response.writeHead(200, {'Content-Type': 'text/html'});

            //파일을 읽어 Body에 기술
            response.write(data.toString());
        }

        response.end();
    });
}).listen(10002);

console.log("일하는 중");

 

 

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>Welcome</title>
    </head>
    <body>
        <h1>Welcome to my castle</h1>
        <hr>
        <h3>Total Amount : 101238000</h3>
    </body>
</html>

 

client.js

var http = require('http');

var options = {
    host: 'localhost',
    port: '10002',
    path:  '/index.html'
}

//callback Function

var callback = function(res){
    //response 이벤트 data 발생 시 데이터를 수신
    var content = '';

    res.on('data', function(data){
        content += data;
    });

    //response 이벤트 중 end 이벤트 발생 시 내용을 출력
    res.on('end', function(){
        //데이터 디스 플레이
        console.log("Data Received");
        console.log(content);
    })
}

var request = http.request(options, callback);
request.end();

'자바 공부 > [자바] 기본 공부' 카테고리의 다른 글

[Vue.js] Componenet  (2) 2024.12.03
[Vue.js] v-문법  (0) 2024.11.28
[Node.js 2일차] 이벤트 처리 함수  (0) 2024.11.28
[Node.js 1일차] Node.js 환경 구축  (1) 2024.11.27
[AJAX] Json 데이터 불러오기  (0) 2024.11.26