Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
文件
This repository doesn't specify license. Please pay attention to the specific project description and its upstream code dependency when using it.
Clone or Download
app.js 2.55 KB
Copy Edit Raw Blame History
br1nosense authored 2023-01-13 22:47 . first
const Koa = require('koa')
const Router = require('koa-router');
const router = new Router();
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const koaBody = require('koa-body');
const conn = require('./db/db')//链接数据库
const index = require('./routes/index')
const users = require('./routes/users')
//jwtoken
const jwt = require("jsonwebtoken")
//撒盐,加密时候混淆
const secret = '123bingjspoiuytrewqlkjhgfdsa'
// 放在路由中间前面
app.use(koaBody());
//生成token
//info也就是payload是需要存入token的信息
function createToken(info) {
let token = jwt.sign(info, secret, {
//Token有效时间 单位s
expiresIn:60 * 60 * 10
})
return token
}
//验证Token
function verifyToken(token) {
return new Promise((resolve, reject) => {
jwt.verify(token, secret, (error, result) => {
if(error){
reject(error)
} else {
resolve(result)
}
})
})
}
// error handler
onerror(app)
// middlewares
app.use(bodyparser({
enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))
app.use(views(__dirname + '/views', {
extension: 'ejs'
}))
// logger
app.use(async (ctx, next) => {
const start = new Date()
await next()
const ms = new Date() - start
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
//测试接口
router.get('/', ctx => {
ctx.body = "Hello Koa !!!!"
})
// routes
app.use(router.routes()).use(router.allowedMethods());
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
// error-handling
app.on('error', (err, ctx) => {
console.error('server error', err, ctx)
});
//设置允许跨域
// app.use(function(req, res, next) {
// //指定允许其他域名访问 *所有
// res.setHeader("Access-Control-Allow-Origin", "*");
// // //允许客户端请求头中带有的
// // res.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
// // //允许请求的类型
// // res.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
// // res.setHeader("X-Powered-By",' 3.2.1')
// //让options请求快速返回
// if(req.method=="OPTIONS") res.send(200);
// else next();
// });
app.listen(3000,()=>{
console.log('正在监听3000端口');
})
module.exports = app
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化