// 可以设置中间件来响应 HTTP 请求。
// 定义了路由表用于执行不同的 HTTP 请求动作
// express内部维护一个函数数组,
// 这个函数数组表示在发出响应之前要执行的所有函数,也就是中间件数组,每一次use以后,
// 传进来的中间件就会推入到数组中,执行完毕后调用next方法执行函数的下一个函数,如果没用调用,调用就会终止。
function express() {
var express = require('express')
var app = express()
app.get('/',(req,res)=>{
res.send('Hello Express!')
})
app.listen(3000)
}
// Koa会把多个中间件推入栈中,与express不同,koa的中间件是所谓的洋葱型模型
function koa(){
const Koa = require('koa');
const app = new Koa();
// x-response-time
app.use(async (ctx, next) => {
const start = new Date();
await next();
const ms = new Date() - start;
ctx.set('X-Response-Time', `${ms}ms`);
});
// logger
app.use(async (ctx, next) => {
const start = new Date();
await next();
const ms = new Date() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});
// response
app.use(ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
// 每一个中间件就类似每一层洋葱圈,上面例子中的第一个中间件 "x-response-time" 就好比洋葱的最外层,第二个中间件 "logger" 就好比第二层,
// 第三个中间件 "response" 就好比最里面那一层,所有的请求经过中间件的时候都会执行两次。
}