what is Express.js
Express.js는 Node.js 환경에서 웹 서버, 또는 API 서버를 제작하기 위해 사용되는 인기 있는 프레임워크입니다.
Expree.js 공식문서 : https://expressjs.com/ko/starter/installing.html
설치
$ mkdir myapp //디렉토리 생성
$ cd myapp //디렉토리 진입
$ npm init
entry point: (index.js)
기본 파일의 이름을 app.js로 입력하거나 자유롭게 입력하십시오. 기본 파일의 이름을 index.js로 입력하기 원하는 경우에는 ENTER 키를 눌러 제안된 기본 파일 이름을 수락하십시오.
$ npm install express --save
$ npm install express //종속항목 저장 안할거면
--save 옵션을 통해 설치된 Node 모듈은 package.json 파일 내의 dependencies 목록에 추가됩니다. 이후 app 디렉토리에서 npm install을 실행하면 종속 항목 목록 내의 모듈이 자동으로 설치됩니다.
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
$ node app.js
를 실행하고, http://localhost:3000/을 실행하면 결과물 확인이 가능하다.$ npm install express-generator -g
$ express -h
Usage: express [options][dir]
Options:
-h, --help output usage information
--version output the version number
-e, --ejs add ejs engine support
--hbs add handlebars engine support
--pug add pug engine support
-H, --hogan add hogan.js engine support
--no-view generate without view engine
-v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
-c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
--git add .gitignore
-f, --force force on non-empty directory
$ express --view=pug myapp
create : myapp
create : myapp/package.json
create : myapp/app.js
create : myapp/public
create : myapp/public/javascripts
create : myapp/public/images
create : myapp/routes
create : myapp/routes/index.js
create : myapp/routes/users.js
create : myapp/public/stylesheets
create : myapp/public/stylesheets/style.css
create : myapp/views
create : myapp/views/index.pug
create : myapp/views/layout.pug
create : myapp/views/error.pug
create : myapp/bin
create : myapp/bin/www
메소드와 URL(/lower, /upper 등)로 분기점을 만드는 것을 라우팅(Routing)이라고 합니다.
클라이언트는 특정한 HTTP 요청 메소드(GET, POST 등)나 서버의 특정 URI(또는 경로)로 HTTP 요청을 보냅니다.
라우팅은 클라이언트의 요청에 해당하는 메소드와 Endpoint에 따라 서버가 응답하는 방법을 결정하는 것입니다.
<라우트의 기본구조>
app.METHOD(PATH, HANDLER)
<예시>
(1) 홈 페이지에서 Hello World!로 응답
app.get('/', function (req, res) {
res.send('Hello World!');
});
(2) 애플리케이션의 홈 페이지인 루트 라우트(/)에서 POST 요청에 응답
app.post('/', function (req, res) {
res.send('Got a POST request');
});
(3) /user 라우트에 대한 PUT 요청에 응답
app.put('/user', function (req, res) {
res.send('Got a PUT request at /user');
});
(4) /user 라우트에 대한 DELETE 요청에 응답
app.delete('/user', function (req, res) {
res.send('Got a DELETE request at /user');
});
(5) 비교해보기
순수한 노드 JS 코드
const requestHandler = (req, res) => {
if(req.url === '/lower') {
if (req.method === 'GET') {
res.end(data)
} else if (req.method === 'POST') {
req.on('data', (req, res) => {
// do something ...
})
}
}
}
Express는 프레임워크 자체에서 라우터 기능
const router = express.Router()
router.get('/lower', (req, res) =>{
res.send(data)
})
router.post('/lower', (req, res) =>{
// do something
})
출처 : 코드스테이츠/ express 공식문서