-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
71 lines (66 loc) · 2.9 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// 导入 express 模块
const express = require('express')
// 创建 express 的服务器实例
const app = express()
// 导入 cors 中间件
const cors = require('cors')
// 将 cors 注册为全局中间件
app.use(cors())
//导入验证规则joi
const joi = require('joi')
//配置解析application/x-www-form-urlencoded 格式的表单数据的中间件
// 托管静态资源文件
app.use('/uploads', express.static('./uploads'))
app.use(express.urlencoded({ extended: false }))
//使用全局错误处理中间件,捕获失败后产生的错误
// 响应数据的中间件
app.use(function(req, res, next) {
// status = 0 为成功; status = 1 为失败; 默认将 status 的值设置为 1,方便处理失败的情况
res.cc = function(err, status = 1) {
res.send({
// 状态
status,
// 状态描述,判断 err 是 错误对象 还是 字符串
message: err instanceof Error ? err.message : err,
})
}
next()
})
// 导入配置文件
const config = require('./config')
// 解析 token 的中间件
const expressJWT = require('express-jwt')
// 只要配置成功了expressJwt中间件就会在req上挂载user
app.use(expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^\/api\//] }));
// 使用 .unless({ path: [/^\/api\//] }) 指定哪些接口不需要进行 Token 的身份认证
// app.use(expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^\/api\//] }))
// 导入并注册用户路由模块
const userRouter = require('./router/user')
app.use('/api', userRouter)
// 导入并使用用户信息路由模块
const userinfoRouter = require('./router/userinfo')
// 注意:以 /my 开头的接口,都是有权限的接口,需要进行 Token 身份认证
app.use('/my', userinfoRouter)
// 导入并使用文章分类路由模块
const artCateRouter = require('./router/artcate')
// 为文章分类的路由挂载统一的访问前缀 /my/article
app.use('/my/article', artCateRouter)
// 导入并使用文章路由模块
const articleRouter = require('./router/article')
// 为文章的路由挂载统一的访问前缀 /my/article
app.use('/my/article', articleRouter)
// 在 app.js 的全局错误级别中间件中,捕获验证失败的错误,并把验证失败的结果响应给客户端
// 定义错误级别的 数据验证中间件
app.use(function(err, req, res, next) {
// 参数校验失败导致的错误
if (err instanceof joi.ValidationError) return res.cc(err)
// 捕获身份认证失败的错误
if (err.name === 'UnauthorizedError') return res.cc('身份认证失败!')
// 未知错误
res.cc(err);
// next();
})
// 调用 app.listen 方法,指定端口号并启动web服务器
app.listen(3007, function() {
console.log('api server running at http://127.0.0.1:3007')
})