import createError from 'http-errors' import express from 'express' import path from 'path' import logger from 'morgan' import cors from 'cors' import session from 'express-session' import { RedisStore } from 'connect-redis' import Redis from 'ioredis' import cookieParser from 'cookie-parser' import indexRouter from './routes/index' import userRouter from './routes/userRouter' import accountRouter from './routes/accountRouter' import { config } from 'dotenv' // mongodb数据库连接 import { connectMongoDB } from './config/mongodbConfig' import { HTTP_STATUS } from './common/constant/httpStatus' import loginUtil from './utils/loginUtil' config() // 初始化 Redis 客户端 const redisClient = new Redis({ host: process.env.REDIS_HOST, port: process.env.REDIS_PORT || 6379, password: process.env.REDIS_PASSWORD, db: 0 }) const app = express() app.use(logger('dev')) app.use(express.json()) app.use(express.urlencoded({ extended: false })) app.use(express.static(path.join(__dirname, 'public'))) app.use(cookieParser()) app.use( session({ name: 'identityKey', store: new RedisStore({ client: redisClient }), secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false, cookie: { httpOnly: true, maxAge: 24 * 60 * 60 * 1000 } }) ) const corsOptions = { origin: 'http://localhost:5173', // 指定允许的源 credentials: true, // 允许发送凭据(如 cookies) optionsSuccessStatus: 200 } app.use(cors(corsOptions)) async function startServer() { try { await connectMongoDB() } catch (error) { console.error('Server error:', error) process.exit(1) } } startServer().then((r) => logger(r)) app.use('/', indexRouter) app.use('/user', loginUtil.authenticateSession, userRouter) app.use('/account', accountRouter) // catch 404 and forward to error handler app.use(function (req, res, next) { next(createError(404)) }) // error handler app.use(function (err, req, res) { // set locals, only providing error in development res.locals.message = err.message res.locals.error = req.app.get('env') === 'development' ? err : {} // render the error page res.status(err.status || HTTP_STATUS.INTERNAL_SERVER_ERROR) res.json({ error: true, message: err.message || 'Something went wrong', // 只在开发环境下返回堆栈信息 ...(req.app.get('env') === 'development' ? { stack: err.stack } : {}) }) }) module.exports = app