expressServer/app.js
LingandRX 4edd3c2a26 refactor: 将项目从 CommonJS 迁移到 ES6 模块
- 更新所有文件的导入和导出语法,使用 ES6 模块格式
- 修改 package.json,添加 "type": "module" 配置
- 调整部分代码结构以适应 ES6 模块
2025-01-04 23:54:03 +08:00

109 lines
2.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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