04-29 02:46
Notice
Recent Posts
Recent Comments
관리 메뉴

Scientific Computing & Data Science

[Web App/Node.js Express4] Express4에서의 라우팅(Routing) 방법 본문

Programming/Web App

[Web App/Node.js Express4] Express4에서의 라우팅(Routing) 방법

cinema4dr12 2014. 9. 13. 14:21

Express가 3.0에서 4.0으로 버전업이 되면서 많은 변화가 있었는데 그 중 하나는 라우팅 방법에 관한 것이다.

이번 글에서는 Express 4에서 라우팅하는 방법에 대해 알아보도록 하겠다.

(예제의 view engine은 ejs로 하였으나, hjs 및 jade도 동일한 방식이 적용된다.)

우선 Express 어플리케이션의 루트 경로의 app.js 파일과 [routes]/index.js 파일은 다음과 같다:

(라우팅에 관한 설명에 초점을 맞추었기 때문에 직접 관련된 명령어만 삽입하였다)


[app.js]

var express = require('express'); var routes = require('./routes/index'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use('/', routes); app.use('/test', routes); ...


[routes/index.js]

var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res) { res.render('index', { title: 'GCHOI' }); }); router.get('/test', function(req, res) { res.render('test', { title: 'HELLO' }); }); module.exports = router;


[views/index.ejs]

<!DOCTYPE html> <html> <head> <title><%= title %></title> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> <h1><%= title %></h1> <p>Welcome to <%= title %></p> </body> </html>


[views/test.ejs]

<!DOCTYPE html> <html> <head> <title><%= title %></title> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> <h1><%= title %></h1> <p>Welcome to <%= title %></p> </body> </html>


([views/index.ejs]와 [views/test.ejs]는 사실 동일하다.)


위의 코드에서 빨간 텍스트로 표현된 부분이 핵심이다.

app.js 파일에서

var routes = require('./routes/index');

[routes]/index.js 파일을 불러오는 부분이며, 변수 routes를 통해 웹 브라우저의 인터넷 주소창에 'localhost:port#/'이 입력될 경우

app.use('/', routes);

이 호출되고 [routes]/index.js 파일에서

router.get('/', function(req, res) { res.render('index', { title: 'GCHOI' }); });

이 실행되면, [views]/index.ejs 파일이 렌더링 된다.

마찬가지로 인터넷 주소창에서 'localhost:port#/test'이 입력되면 app.js

app.use('/test', routes);

이 실행되어 [routes]/index.js 파일에서

router.get('/test', function(req, res) { res.render('test', { title: 'HELLO' }); });

에 의해 [views]/test.ejs 파일이 렌더링 된다.



별 내용 없지만 과정이 꽤 복잡해 보인다. 엑기스만 추출하여 설명하면 다음과 같다:

(1) app.js

app.use('/YOUR_PATH', routes);

(2) routes/index.js

router.get('/YOUR_PATH', function(req, res) { res.render('test', { ... }); });

(3) views/test.ejs

<!DOCTYPE html> <html> <head> ... </head> <body> ... </body> </html>


Comments