Node.js #4 (웹서버 만들기)

박준석·2023년 3월 2일
0

Node.js

목록 보기
4/12
post-thumbnail

웹서버 만들기

WEB Browser가 있고 WEB Server있으면 WEB Browser가 우리가 주소를 입력해서 요청을 하면 WEB Server는 그 요청에 따른 정보를 찾아서 응답 해주는 관계이다.

Node.js도 웹서버를 만들 수 있다.

Node.js로 먼저 웹서버를 만들어 보자.

먼저 index.html 파일을 만들어 원하는 내용을 작성한다.

<!doctype html>
<html>
<head>
  <title>WEB1 - Welcome</title>
  <meta charset="utf-8">
</head>
<body>
  <h1><a href="index.html">WEB</a></h1>
  <ol>
    <li><a href="1.html">HTML</a></li>
    <li><a href="2.html">CSS</a></li>
    <li><a href="3.html">JavaScript</a></li>
  </ol>
  <h2>WEB</h2>
  <p>The World Wide Web (abbreviated WWW or the Web) is an information space where documents and other web resources are identified by Uniform Resource Locators (URLs), interlinked by hypertext links, and can be accessed via the Internet.[1] English scientist Tim Berners-Lee invented the World Wide Web in 1989. He wrote the first web browser computer program in 1990 while employed at CERN in Switzerland.[2][3] The Web browser was released outside of CERN in 1991, first to other research institutions starting in January 1991 and to the general public on the Internet in August 1991.
  </p>
</body>
</html>

만들고 나면 javascript 파일을 만들어 다음과 같은 코드를 작성한다.

var http = require('http');
var fs = require('fs');
var app = http.createServer(function(request,response){
    var url = request.url;
    if(request.url == '/'){
      url = '/index.html';
    }
    if(request.url == '/favicon.ico'){
      return response.writeHead(404);
    }
    response.writeHead(200);
  	console.log(__dirname + url);
    response.end(fs.readFileSync(__dirname + url));
    //javascript를 통해서 우리가 읽어드려야 하는 파일을 만든 것이다.
    // 사용자가 생성한 파일을 전송한다.
});
app.listen(3000); //포트 번호를 3000번으로 지정

에디터를 열어 node main.js를 입력하면 다음과 같이 뜬다.

그리고 인터넷을 열어 url 검색창에 localhost:3000 입력하면 다음과 같은 화면이 나온다.

에디터에는 console.log를 했기 때문에 내가 열 페이지를 전송하는 것을 볼 수 있다.

위 화면에서 HTML을 클릭하면 웹페이지에 전송될 데이터들이 전송되는 것을 볼 수 있다.

또 쿠키가 저장 되기 때문에 다시 서버를 연결해도 내가 연 페이지 그대로 되어있다.

profile
안녕하세요 프론트엔드 개발자입니다. 글을 이전 중입니다.

0개의 댓글