import dotenv from 'dotenv';
dotenv.config();
import express from 'express';
import morgan from 'morgan';
import cookieParser from 'cookie-parser';
import session from 'express-session';
import multer from 'multer';
import fs from 'fs';
import path from 'path';
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(morgan('dev'));
app.use(
session({
resave: false,
saveUninitialized: false,
secret: process.env.COOKIE_SECRET,
cookie: {
httpOnly: true,
secure: false,
},
name: 'session-cookie',
})
);
app.use('/', (req, res, next) => {
console.log(req.session.id);
console.log('세션이름', req.session.name);
if (req.session.name) {
express.static(path.join(__dirname, 'public305'))(req, res, next);
} else {
next();
}
});
app.use(cookieParser(process.env.COOKIE_SECRET));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
try {
fs.readdirSync('uploads');
} catch (error) {
console.error('uploads 폴더가 없어 uploads 폴더를 생성합니다.');
fs.mkdirSync('uploads');
}
const upload = multer({
storage: multer.diskStorage({
destination(req, file, done) {
done(null, 'uploads/');
},
filename(req, file, done) {
const ext = path.extname(file.originalname);
done(null, path.basename(file.originalname, ext) + Date.now() + ext);
},
}),
limits: { fileSize: 5 * 1024 * 1024 },
});
app.get('/upload', (req, res) => {
res.sendFile(path.join(__dirname, 'multipart.html'));
});
app.post('/upload', upload.single('image'), (req, res) => {
console.log(req.file);
res.redirect('http://localhost:3025/upload');
});
app.post('/uploads', upload.array('image'), (req, res) => {
console.log(req.files);
console.log(req.body.title);
res.redirect('http://localhost:3025/upload');
});
app.post(
'/uploadf',
upload.fields([
{ name: 'image1', maxCount: 2 },
{ name: 'image2', maxCount: 1 },
]),
(req, res) => {
console.log('이미지1', req.files.image1);
console.log('이미지2', req.files.image2);
console.log(req.body.title);
res.redirect('http://localhost:3025/upload');
}
);
app.use((req, res, next) => {
req.data = '요청 한번동안 일회성 데이터전달 가능';
next();
});
app.get(
'/',
(req, res, next) => {
console.log(req.data);
next('route');
},
(req, res) => {
throw new Error('에러는 에러 처리 미들웨어로 갑니다.');
}
);
app.get('/', (req, res) => {
req.session.name = '세션 등록용 테스트!!';
console.log('세션아이디', req.sessionID);
res.sendFile(path.join(__dirname, 'index.html'));
});
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(app.get('port'), '번 포트에서 대기 중');
});