티스토리 뷰

2017/01/05 - [컴퓨터/node.js] - node.js ) 번외 - Express Framework 및 jade

2016/12/21 - [컴퓨터/node.js] - node.js ) 6일차 - 의존성

2016/12/17 - [컴퓨터/node.js] - node.js ) 5일차 - 모듈화

2016/12/17 - [컴퓨터/node.js] - node.js ) 4일차 - 이벤트형 처리

2016/12/16 - [컴퓨터/node.js] - node.js ) 3일차 - 함수 작성

2016/12/16 - [컴퓨터/node.js] - node.js ) 2일차 - 웹서버 구동

2016/12/16 - [컴퓨터/node.js] - node.js ) 1일차 - Hello World !



오늘은 Node.js Express Framework 를 이용해 html 파일로 index.html  과 about.html  까지만 실행해보쟈


1. 작업 폴더를 만든다.


[root@localhost node_test]# mkdir node_7

[root@localhost node_test]# cd node_7




2. package.json 을 생성한다.


package.json 은 프로젝트 폴더 root에 존재하면서, 프로젝트에 필요한 모듈, 의존성 등을 명시해 놓는 안드로이드의 Menifest.xml 같은 역할 (인듯?)


{

  "name": "marlboroyw",

  "version": "1.0.0",

  "dependencies":

  {

    "express": "~4.13.1",

    "ejs": "~2.4.1"

  }

}



name : 프로젝트 이름

version : 프로젝트 버전

dependencies : 프로젝트 의존성




3. npm install : NPM  Dependencies (의존성) 설치


package.json 을 작성한 후, 해당 폴더에서 npm install 을 타이핑 하면 package.json의 내용대로 의존성 모듈들을 설치한다. 한번 해보자.

[root@localhost node_7]# npm install

npm WARN npm npm does not support Node.js v0.10.46

npm WARN npm You should probably upgrade to a newer version of node as we

npm WARN npm can't make any promises that npm will work with this version.

npm WARN npm You can find the latest version at https://nodejs.org/

marlboroyw@1.0.0 /home/yw/node_test/node_7

── ejs@2.4.2 

└─ express@4.13.4 

  accepts@1.2.13 

  │ mime-types@2.1.13 

  │ │ └── mime-db@1.25.0 

  │ └── negotiator@0.5.3 

  ── array-flatten@1.1.1 

  ── content-disposition@0.5.1 

  ── content-type@1.0.2 

  ── cookie@0.1.5 

  ── cookie-signature@1.0.6 

  debug@2.2.0 

  │ └── ms@0.7.1 

  ── depd@1.1.0 

  ── escape-html@1.0.3 

  ── etag@1.7.0 

  finalhandler@0.4.1 

  │ └── unpipe@1.0.0 

  ── fresh@0.3.0 

  ── merge-descriptors@1.0.1 

  ── methods@1.1.2 

  on-finished@2.3.0 

  │ └── ee-first@1.1.1 

  ── parseurl@1.3.1 

  ── path-to-regexp@0.1.7 

  proxy-addr@1.0.10 

  │ ── forwarded@0.1.0 

  │ └── ipaddr.js@1.0.5 

  ── qs@4.0.0 

  ── range-parser@1.0.3 

  send@0.13.1 

  │ ── destroy@1.0.4 

  │ http-errors@1.3.1 

  │ │ └── inherits@2.0.3 

  │ ── mime@1.3.4 

  │ └── statuses@1.2.1 

  serve-static@1.10.3 

  │ └── send@0.13.2 

  type-is@1.6.14 

  │ └── media-typer@0.3.0 

  ── utils-merge@1.0.0 

  └── vary@1.0.1 


npm WARN marlboroyw@1.0.0 No description

npm WARN marlboroyw@1.0.0 No repository field.

npm WARN marlboroyw@1.0.0 No license field.


뭐가 막 깔렸다고 하는디 폴더에 뭐가 생겼나 한번 보자. (ls -al)

[root@localhost node_7]# ls -al

합계 16

drwxr-xr-x  3 root root 4096  1월  8 21:27 .

drwxr-xr-x 10 root root 4096  1월  8 20:00 ..

drwxr-xr-x 44 root root 4096  1월  8 21:28 node_modules

-rw-r--r--  1 root root  127  1월  8 21:27 package.json


맨첨에 만들었던 package.json말고, node_modules 라는 폴더가 생성되었고, 이 안에 여러 모듈들이 들어가 있다.




4. server.js 생성


[root@localhost node_7]# vi server.js


var express = require('express');

var app = express();

var server = app.listen(4000, function(){

    console.log("Express server has started on port 4000")

})


아무것도 없는 4000 포트의 빈 서버이다.

Client 가 접속하면 간단한 로그만 찍는게 다지만 실행시켜 보자


[root@localhost node_7]# node server.js

Express server has started on port 4000






" Cannot GET / " 문구가 보이면 성공이다.


get request 를 받았을때 노드서버에서 아무것도 리턴해 주는 것이 없기 때문이다.

이제 html 페이지를 만들어보자.




5. get 요청을 받을 router 생성


이전 글에서 우리는 모든것을 server.js에서 받는 것은 매우 비 효율적이라는 것을 알았다.

따라서 router 를 생성하여 페이지들을 연결시켜 보자.


[root@localhost node_7]# mkdir router

[root@localhost node_7]# cd router/


router 폴더에서 main.js 를 생성하여 get 요청을 받았을때의 동작을 지정해보자.


[root@localhost router]# vi main.js


module.exports = function(app)

{

     app.get('/',function(req,res){

        res.render('index.html')

     });

     app.get('/about',function(req,res){

        res.render('about.html');

    });

}


간단하다. 

/ 로 접근하면 index.html 을, /about 으로 접근하면 about.html 을 보여주는 것이다. 

하지만 지금은 html 페이지가 없다. 우리가 만들어보자.

우선 router 폴더에서 나와서, views 폴더를 생성한다.


[root@localhost router]# cd ..

[root@localhost node_7]# mkdir views

[root@localhost node_7]# cd views/


왜 굳이 이렇게 해야 하느냐라고 묻는다면..구글신에게

node.js express 구조 를 검색해서 이해하고 오시는것을 추천드린다.


자 이제 view 폴더안에 각각 index.html과 about.html 파일을 생성한다.


거의 다 왔다. 


이제 view 파일도 있고, get 요청을 처리해줄 router도 있다.

이제 뭐만 해주면 될까?


server.js와 router 만 연결시켜 주면 된다.


server.js를 아래와 같이 편집한다.


var express = require('express');

var app = express();

var router = require('./router/main')(app);

 

app.set('views', __dirname + '/views');

app.set('view engine', 'ejs');

app.engine('html', require('ejs').renderFile);

 

var server = app.listen(4000, function(){

    console.log("Express server has started on port 4000")

});




6. 서버 실행


서버를 실행해 보자

[root@localhost node_7]# node server.js 

Express server has started on port 4000


이제 브라우저에 접속하면 아래와 같이 보인다.



루트 접속시




/about 접속시







공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함