- 更新导入路径,使用 .js 后缀 -修正用户模型中的密码加密和验证逻辑 - 优化用户路由和控制器 - 重构用户服务和仓库,使用原生 mongoose 方法- 更新错误处理和日志记录
97 lines
2.5 KiB
JavaScript
97 lines
2.5 KiB
JavaScript
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 { fileURLToPath } from 'url'
|
||
import cookieParser from 'cookie-parser'
|
||
import indexRouter from './routes/index.js'
|
||
import userRouter from './routes/userRouter.js'
|
||
import accountRouter from './routes/accountRouter.js'
|
||
import { config } from 'dotenv'
|
||
import { connectMongoDB } from './config/mongodbConfig.js'
|
||
import { HTTP_STATUS } from './common/constant/httpStatus.js'
|
||
import { authenticateSession } from './utils/loginUtil.js'
|
||
|
||
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()
|
||
|
||
const __filename = fileURLToPath(import.meta.url)
|
||
const __dirname = path.dirname(__filename)
|
||
|
||
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', 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 } : {})
|
||
})
|
||
})
|
||
|
||
export default app
|