alioth/before/cha/01===sys22/baseSys/userSys/realization/app.js
2025-05-30 09:18:01 +08:00

118 lines
4.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// koa-router提供全面的路由功能比如类似Express的app.get/post/put的写法URL命名参数、路由命名、嵌套路由、支持加载多个中间件
// koa-bodyparserpost提交数据中间件解析请求体时需要加载的中间件支持x-www-form-urlencoded, application/json等格式的请求体不支持form-data的请求体
// koa-views对进行视图模板渲染支持ejs, nunjucks等模板引擎
// koa-static静态资源中间件用作类似Nginx的静态文件服务在本地开发时可用于加载前端文件或后端Fake数据
// koa-sessionsession验证支持将会话信息存储在本地Cookie或Redis, MongoDB
// koa-jwttoken验证路由权限控制功能Session Base转为用Token Base
// koa-helmet网络安全增加Strict-Transport-Security, X-Frame-Options, X-Frame-Options等HTTP头提高应用程序的安全性
// koa-compress当响应体较大时启用类似Gzip的压缩技术减少传输内容
// koa-logger输出请求日志的功能包括请求的url、状态码、响应时间、响应体大小等信息
// koa-convert基于Promise的中间件和基于Generate的中间件相互转换
// koa-nunjucks-2轻量级 Nunjucks 中间件可以用作模板引擎为koa应用提供页面渲染功能
// koa-favicon页面logo加载
// koa-jsonget提交数据的中间件
// koa-onerror在服务器产生错误throw 抛出等)后自动重定义到指定路径
// koa-respond在Koa上下文中添加了常用的方法
/**
* 添加依赖
* */
const Koa = require('koa')// 主依赖 Koa2
, logger = require('koa-logger')// 日志
// , bodyparser = require('koa-bodyparser')// 获取body的参数post,支持x-www-form-urlencoded, application/json等格式的请求体不支持form-data的请求体
, koaBody = require('koa-body')// 支持form-data支持文件不支持x-www-form-urlencoded不可同时使用
global.path = __dirname
/**
* 路由
* */
const router = require('./src/Routes/index')
/**
* 创建应用程序
* */
const app = new Koa();
// 数据库操作
// databaseOperation()
// 请求日志
app.use(logger());
// 时间
app.use(printMethod());
// ctx.request.body body参数
// 已过时被koa-body替代
// app.use(bodyparser({
// enableTypes: ['json', 'form', 'text']
// }))
app.use(koaBody({
multipart:true, // 支持文件上传
encoding:'gzip',
strict:false,// 参数:如果启用则不解析GETHEADDELETE请求默认为true
formidable:{
// uploadDir:path.join(__dirname,'public/upload/'), // 设置文件上传目录
keepExtensions: true, // 保持文件的后缀
maxFieldsSize:2 * 1024 * 1024, // 文件上传大小
// onFileBegin:(name,file) => { // 文件上传前的设置
// // console.log(`name: ${name}`);
// // console.log(file);
// },
}
}));
// token
app.use(verToken())
// 路由
app.use(router.routes(), router.allowedMethods({
// throw: true, // 抛出错误,代替设置响应头状态
// notImplemented: () => '不支持当前请求所需要的功能',
// methodNotAllowed: () => '不支持的请求方式'
}));
// veriToken
function verToken(){
return async function(ctx, next){
// 请求地址判断
if(ctx.req.url.indexOf('/api/user/will') == 0){
await next()
}else{
const token = ctx.request.header.authorization
const result2 = global.token.decrypt(token)
// 判断此Token有没有过期
if(result2.token){
const result = await global.Redis.getToken(token)
// 判断Redis是否有此token
if(result){
ctx.uuid = result2.id.uuid
ctx.token = token
await next()
}else{
ctx.body = global.msg.failed({}, '账户令牌失效!', true)
}
}else{
ctx.body = global.msg.failed({}, '账户令牌失效。', true)
}
}
}
}
// 打印时间
function printMethod() {
return async function (ctx, next) {
const start = new Date()
await next()
const ms = new Date() - start
console.info(`Method ${ctx.method} ${ctx.url} - ${ms}ms`)
}
}
setTimeout(other)
function other(){
console.w('other test')
console.w(global.path)
}
module.exports = app;