You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
46 lines
1.3 KiB
46 lines
1.3 KiB
require('dotenv').config();
|
|
const express = require('express');
|
|
const mongoose = require('mongoose');
|
|
const cors = require('cors');
|
|
const morgan = require('morgan');
|
|
|
|
// 导入路由
|
|
const authRoutes = require('./routes/auth');
|
|
const examRoutes = require('./routes/exams');
|
|
const resultRoutes = require('./routes/results');
|
|
|
|
// 初始化应用
|
|
const app = express();
|
|
|
|
// 中间件
|
|
app.use(cors());
|
|
app.use(morgan('dev'));
|
|
app.use(express.json());
|
|
|
|
// 数据库连接
|
|
mongoose.connect(process.env.MONGODB_URI)
|
|
.then(() => console.log('Connected to MongoDB'))
|
|
.catch(err => console.error('MongoDB connection error:', err));
|
|
|
|
// 路由
|
|
app.use('/api/auth', authRoutes);
|
|
app.use('/api/exams', examRoutes);
|
|
app.use('/api/results', resultRoutes);
|
|
|
|
// 错误处理中间件
|
|
app.use((err, req, res, next) => {
|
|
console.error(err.stack);
|
|
res.status(500).json({ message: 'Something went wrong!' });
|
|
});
|
|
|
|
// 启动服务器
|
|
const PORT = process.env.PORT || 5000;
|
|
app.listen(PORT, () => {
|
|
console.log(`Server running on port ${PORT}`);
|
|
});
|
|
// 在app.js中添加更详细的CORS配置
|
|
app.use(cors({
|
|
origin: 'http://localhost', // 或你的前端实际域名
|
|
methods: ['GET', 'POST', 'PUT', 'DELETE'],
|
|
allowedHeaders: ['Content-Type', 'Authorization']
|
|
})); |