principle:
- The method of use of the object instance koa callback function, as in the following example App.use ((ctx, next) => {}), there is ctx, next two parameters.
- Can ctx's request, response object, you can end accordingly, will call the next middleware only call next (), if not called, next method, we can not continue with the next middleware
application:
- Application Middleware
When the request just entered service, the function must be performed, can be achieved through the middleware
/**
* 应用级别中间件
* */
const Koa = require('koa');
const Router = require('koa-router')();
const App = new Koa();
App.use((ctx,next)=>{
ctx.body = {};
ctx.body.date = new Date();
next()
});
Router.get('/',function (ctx,next) {
ctx.body.content='hello world'
})
Router.get('/news',function (ctx,next) {
ctx.body.content = "新闻页面"
})
App.use(Router.routes());
App.use(Router.allowedMethods());
App.listen(3000,()=>{
console.log('queck start at port 3000')
})
- Route Middleware
Do something before a request
/**
* 应用级别中间件
* */
const Koa = require('koa');
const Router = require('koa-router')();
const App = new Koa();
Router.get('/',function (ctx,next) {
ctx.body ={};
console.log('请求了/');
next();
})
Router.get('/news',function (ctx,next) {
ctx.body ={};
console.log('请求了/news');
next();
})
Router.get('/',function (ctx,next) {
ctx.body.content='hello world'
})
Router.get('/news',function (ctx,next) {
ctx.body.content = "新闻页面"
})
App.use(Router.routes());
App.use(Router.allowedMethods());
App.listen(3000,()=>{
console.log('queck start at port 3000')
})
Access http: // localhost: 3000 'requested /' {content: 'hello world'}
Visit http: // localhost: 3000 / news 'requests / news' {content: 'news page'}