import express from 'express';
import path from 'path';
import indexRouter from './routes/index.js';
import userRouter from './routes/user.js';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
app.set('port', process.env.PORT || 3000);
app.use((req, res, next) => {
console.log('미들웨어(콜백함수)는 모든 요청에 다 실행되어 공통으로 실행할 것들의 중복을 제거해줍니다.');
next();
});
app.use(
'/about',
(req, res, next) => {
console.log('미들웨어(콜백함수)를 어바웃 요청에서만 실행');
next();
},
(req, res, next) => {
console.log('미들웨어(콜백함수)를 어바웃 요청에서만 두번째실행');
next();
}
);
app.use('/user', userRouter);
app.get('/', (req, res) => {
console.log('host', req.get('host'));
res.sendFile(path.join(__dirname, 'index.html'));
});
app.get(
'/category/:name',
(req, res, next) => {
+req.params.name ? next() : next('route');
},
(req, res, next) => {
try {
throw new Error('에러발생!');
} catch (error) {
next(error);
}
}
);
app.get('/category/:name', (req, res) => {
res.send(`${req.params.name}`);
});
app.get('/category', (req, res) => {
res.send('category!');
});
app.use((req, res, next) => {
res.status(404).send('404 Page Not Found');
});
app.use((err, req, res, next) => {
console.error(err);
res.status(500).send(err.message);
});
app.listen(app.get('port'), () => {
console.log('익스프레스 서버 실행');
});