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.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
const express = require ( 'express' ) ;
const cors = require ( 'cors' ) ;
require ( 'dotenv' ) . config ( ) ; // 加载.env环境变量
// 导入数据库连接测试和登录路由
const { testDbConnection } = require ( './config/db' ) ;
const userRoutes = require ( './routes/userRoutes' ) ;
// 初始化Express应用
const app = express ( ) ;
// 1. 配置中间件(必须在挂载路由前)
// 解析JSON请求体( 登录时前端传的用户名/密码会用JSON格式)
app . use ( express . json ( ) ) ;
// 解析表单请求体(兼容其他场景,如表单提交)
app . use ( express . urlencoded ( { extended : true } ) ) ;
// 配置跨域( 允许uni-app前端地址访问, 从.env读取配置)
app . use ( cors ( {
origin : process . env . CORS _ORIGIN ,
credentials : true // 允许携带Cookie, 后续若需记住登录状态可用
} ) ) ;
// 配置静态资源服务
app . use ( '/uploads' , express . static ( 'uploads' ) ) ;
// 2. 测试数据库连接(启动时自动验证)
testDbConnection ( ) ;
// 3. 挂载路由(所有接口加/api前缀, 避免路径冲突)
// 登录接口最终地址: http://localhost:3000/api/login
app . use ( '/api' , userRoutes ) ;
// 4. 全局错误处理中间件(捕获接口异常,返回统一错误格式)
app . use ( ( err , req , res , next ) => {
console . error ( '服务器异常:' , err . stack ) ;
res . status ( 500 ) . json ( {
code : 500 ,
msg : '服务器内部错误' ,
error : err . message
} ) ;
} ) ;
// 导入产品路由
const productRoutes = require ( './routes/productRoutes' ) ;
// 挂载产品路由
app . use ( '/api' , productRoutes ) ;
// 导出app实例, 给server.js调用
module . exports = app ;