1 Star 2 Fork 0

God_first/api_server

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
app.js 2.18 KB
一键复制 编辑 原始数据 按行查看 历史
God_first 提交于 2021-03-01 19:50 . 完成文章分类功能
const express = require('express');
const app = express();
const userRouter = require('./router/user');
// 引入express - joi包( 解析token值)
const jwtPaeser = require('express-jwt');
// 引入 cors中间件
const cors = require('cors');
const { required } = require('@hapi/joi');
// 引入配置文件
const config = require('./config');
// 引入用户路由中心模块
const userinfoRouter = require('./router/userinfo');
//引入文章类别的路由模块
const cateRouter = require('./router/cate')
// 将cors注册为全局中间件
app.use(cors());
// 配置解析 application/x-www-form-urlencoded 格式的表单数据的中间件:
app.use(express.urlencoded({ extended: false }));
// 在路由模块之前,注册一个全局中间件对错误的情况进行处理
app.use((req, res, next) => {
res.cc = (err, status = 1) => { //status =1 表示默认值为1,err错误消息
res.send({
status,
// instanceof用来判断对象的类型
message: err instanceof Error ? err.message : err
})
}
next();
})
// 在路由模块前,解析token中间件
// 全局注册 jwt 中间件
// secret 是生成 jwt 时的秘钥; alg 是生成 jwt 时的加密算法
// .unless({ path: [/^\/api\//] }) 指定哪些接口不需要进行 jwt 的身份认证
app.use(jwtPaeser({ secret: config.tokenSecret, algorithms: ['HS256'] }).unless({ path: [/^\/api\//] }));
// app.get('/my', (req, res) => {
// return res.send('ok!')
// })
// 在全局中间件的下面注册引入路由模块
app.use('/api', userRouter);
// 在全局中间件的下面注册引入个人中心路由模块
app.use('/my', userinfoRouter);
//在全局中间件的下面引入文章类别路由模块
app.use('/my', cateRouter)
// 末尾,注册全局错误处理中间件
app.use((err, req, res, next) => {
// 判断用户token是否授权
if (err.name === 'UnauthorizedError') {
return res.send({
status: 1,
message: '身份认证失败!'
})
}
// 调用res上挂载的cc()方法
res.cc(err);
next();
})
app.listen(3007, () => {
console.log('运行服务成功: http://127.0.0.1:3007');
})
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/god-first/api_server.git
git@gitee.com:god-first/api_server.git
god-first
api_server
api_server
master

搜索帮助