中间件(洋葱模型)、放在中间件中的常用模块
app.use(async (ctx,next)=>{
.......
await next();
.......
})
- koa-bodyparser模块,接收post请求传俩的参数
const bodyparse = require('koa-bodyparser');
app.use(bodyparse());
const { name } = ctx.request.body;
const cors = require('koa2-cors');
app.use(cors({
origin: function (ctx) {
return 'http://localhost:8080';
},
exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
maxAge: 5,
credentials: true,
allowMethods: ['GET', 'POST', 'DELETE'],
allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))
const staticFiles = require('koa-static')
app.use(static('./static'));
const log4js = require('log4js');
const logjs = (app) => {
app.use(async (ctx,next) => {
log4js.configure({
appenders: { cheese: { type: 'file', filename: 'cheese.log' } },
categories: { default: { appenders: ['cheese'], level: 'error' } }
});
const logger = log4js.getLogger('cheese');
await next();
})
}
module.exports = logjs;
- 状态码处理
– 返回404页面,node是不会报错的。
– 利用洋葱模型,将捕获错误码页面,放在最外一层洋葱层,捕获next()里面所有的错误码。
app.use(async (ctx,next)=>{
try{
await next();
if(ctx.response.status === 404 && !ctx.response.body){
ctx.throw(404);
}
}
catch(err){
let fileName;
let status = parseInt(e.status);
const message = e.message;
if(status >= 404){
switch(status){
case 400:
case 500:
case 404:
fileName = status;
break;
default:
fileName = 'other';
}
}
ctx.body = fileName;
}
})
错误处理加日志处理网址
https://blog.youkuaiyun.com/qq8344310/article/details/100677139
路由
router.get('/:id',async (ctx,next) => {
})
router.get('/:name/aaa',async (ctx,next) => {
})
const router = new Router({
prefix: '/users'
});
- redirect 重定向 ctx.redirect(’/sign’)
ctx.redirect('/sign')
- status 返回状态码 ctx.status = 200
ctx.status = 200