이 글에서 다룰 내용은 Express를 이용해 웹페이지를 구현하기 위해 가장 기본적인 Routing 방법이다.
먼저 전체 코드를 본 뒤 하나씩 알아가보도록 하자.
var express = require('express'); var app = express(); var getHtml = function(title,style,subtitle,description) { return `<!doctype html> <html> <head> <title>${title}</title> <meta charset="utf-8"> </head> ${style} <body> <h1>${subtitle}</h1> <des>${description}</des> </body> </html>`; } app.get('/',function(request,response) { var title = 'Example'; var subtitle = 'This is Subtitle'; var description = 'This is Express Example'; var html = getHtml(title,'',subtitle,description); response.send(html); }); app.get('/coffee',function(request,response) { var title = 'Coffee'; var subtitle = 'Would you like some coffee?'; var style = `<style> body { background-color:Beige } des { color: Brown } </style>` var description = 'my favorite coffee is vanila latte'; var html = getHtml(title,style,subtitle,description); response.send(html); }); app.use(function(req,res,next){ console.log('Something error'); res.status(404).send('Sorry cant find that'); }); app.listen(3000,function() { console.log('Routing success'); });
Express는 기본적으로 app.METHOD를 통해 Routing을 한다.
METHOD에는 Express가 제공하는 HTTP request와 대응되는 method들이 올 수 있다. get, post 등등.
오늘은 아주 기본적인 app.get을 통해 웹페이지를 구현하자.
코드 내의 app.get 함수의 argument들을 한번 살펴보면, 첫 번째 인자로 path가 오고, 두 번째 인자로 callback 함수가 온다.
이는 웹페이지 주소가 해당 첫 번째 인자로 들어온 path일 때 두 번째 인자로 들어온 callback 함수를 실행한다.
만약 웹페이지 주소가 http://localhost:3000/ 일때는 19 Line의 app.get 함수를 따르고,
http://localhost:3000/coffee 일때는 27 Line의 app.get 함수를 따른다.
callback 함수의 마지막에는 response.send(html);이 있는데, 이를 통해 웹페이지의 실질적인 화면을 구성하는
HTML을 사용자에게 뿌려준다고 할 수 있다.
해당 코드를 실행한 후 웹페이지를 켜보면 다음과 같은 결과가 나온다.
path가 '/'일 때와 '/coffee'일 때의 결과화면이 각 app.get 함수에서 구성한 html 변수에 따라 다른 것을 알 수 있다.
마찬가지로 response.send(html); 을 통해 웹페이지의 화면을 해당 html으로 구성한다는 것을 알 수 있다.
'WEB' 카테고리의 다른 글
[JavaScript] jQuery Effects(3) - Slide (0) | 2019.02.21 |
---|---|
[JavaScript] jQuery Effects(2) - Fade (0) | 2019.02.21 |
[JavaScript] jQuery Effects (1) - Hide/Show (0) | 2019.02.20 |
[Javascript] Mouse Events 정리 (0) | 2019.02.19 |
[Javascript] 특정 태그 선택하기 (0) | 2019.01.10 |