http 모듈로 웹 서버를 만들 때 코드가 보기 좋지 않고, 확장성도 떨어짐
⇒ 프레임 워크로 해결
Express, Koa, Hapi{
"name": "learn-express",
"version": "0.0.1",
"scripts": {
"start": "nodemon app"
},
"devDependencies": {
"nodemon": "^2.0.3"
},
"dependencies": {
"cookie-parser": "^1.4.5",
"express": "^4.17.1",
"express-session": "^1.17.1",
"morgan": "^1.10.0"
}
}
"scripts": { "start": "nodemon app" } 를 작성해 두면
⇒ `npm run start` 또는 `npm start` 를 통해 실행시킬 수 있음
const express = require('express');
const path = require('path');
const app = express();
app.set('port', process.env.PORT || 3000);
app.get('/', (req, res) => {
// res.send('Hello, Express');
res.sendFile(path.join(__dirname, '/index.html'));
});
app.listen(app.get('port'), () => {
console.log(app.get('port'), '번 포트에서 대기 중');
});
nodemon app 으로 실행시키면 프로젝트 파일이 바뀌었는지 여부를 검사해서 알아서 잘 처리해줌~ 알아서 재 시작 하고 에러 띄우고~res.sendFile(path.join(__dirname, '/index.html')); 이 코드가 실행이 되면서 그때 그때 html을 읽어서 보여줌app.set('port', 포트) 로 서버가 실행될 포트 지정app.get('주소', 라우터)로 GET 요청이 올 때 어떤 동작을 할지 지정app.listen('포트', 콜백)으로 몇 번 포트에서 서버를 실행할 지 지정app.js : 핵심 서버 스크립트
public : 외부에서 접근 가능한 파일들 모아둠
views : 템플릿 파일을 모아둠
routes : 서버의 라우터와 로직을 모아둠
(추후에 models를 만들어 데이터베이스 사용)
익스프레스는 미들웨어로 구성됨
app.get()에 공통된 코드를 app.use()에 묶어 한번에 처리 가능!
...
app.set('port', process.env.PORT || 3000);
app.get('/', (req, res, next) => {
console.log('모든 요청에 다 실행됨');
next();
});
app.get('/', (req, res, next) => {
console.log('GET / 요청에서만 실행됩니다.');
next();
}, (req, res) => {
throw new Error('에러는 에러 처리 미들웨어로 갑니다.')
});
app.use((err, req, res, next) => {
console.error(err);
res.status(500).send(err.message);
});
...
와일드카드~
app.get('/category/:name', (req, res, next) => {
console.log(`hello ${req.params.name}`);
});
카테고리 하위에서는 모두 동작함!
app.get('/category/test', ... 처럼 또 지정해 준 게 있어도 와일드 카드부분 소스가 먼저 나오면 우선 실행
그래서 와일드 카드는 다른 카테고리보다 소스 코드 순서 상 아래에 위치 해야 함
app.get('/category/test', (req, res, next) => {
console.log('hello test');
});
//와일드 카드 포함 된 코드를 더 아래에 작성
app.get('/category/:name', (req, res, next) => {
console.log(`hello ${req.params.name}`);
});
모든 것에 대해 처리하는 *도 하위에 넣어주어야 문제 발생하지 않음
app.get('*', (req, res, next) => {
console.log('hello everybody');
});