新建文件夹 koa
执行
npm install koa
新建一个app.js
内容如下:
// 导入koa,和koa 1.x不同,在koa2中,我们导入的是一个class,因此用大写的Koa表示:
const Koa = require('koa');
// 创建一个Koa对象表示web app本身:
const app = new Koa();
// 对于任何请求,app将调用该异步函数处理请求:
app.use(async (ctx, next) => {
await next();
ctx.response.type = 'text/html';
ctx.response.body = '<h1>Hello, koa2!</h1>';
});
// 在端口3000监听:
app.listen(3000);
console.log('app started at port 3000...');
执行
node app.js
想要优化命令行
新建package.json 在里面添加如下
"scripts": {
"start": "node app.js"
},
npm run start
每个 await next() 使koa形成一个调用链 一个async调用下一个async ,每个async是一个中间件 middleware
看下面一个例子打印的顺序是什么:
// 导入koa,和koa 1.x不同,在koa2中,我们导入的是一个class,因此用大写的Koa表示:
const Koa = require('koa');
// 创建一个Koa对象表示web app本身:
const app = new Koa();
app.use(async (ctx, next) => {
console.log(`${ctx.request.method} ${ctx.request.url}`); // 打印URL
await next(); // 调用下一个middleware
});
app.use(async (ctx, next) => {
const start = new Date().getTime(); // 当前时间
await next(); // 调用下一个middleware
const ms = new Date().getTime() - start; // 耗费时间
console.log(`Time: ${ms}ms`); // 打印耗费时间
});
app.use(async (ctx, next) => {
await next();
ctx.response.type = 'text/html';
ctx.response.body = '<h1>Hello, koa2!</h1>';
console.log(`last最后一步`); // 最后结尾
});
// 在端口3000监听:
app.listen(3000);
console.log('app started at port 3000...');
首先 先打印url 再渲染页面 最后看渲染页面需要多久
打印顺序为:
结果跟我们想象的是一致的
如果说一个use里面没有async的话 后续的middleware就不会往下走了,上面的例子 我们渲染完成之后不添加 async await的话 咱们看下打印的是什么
打印没变 是不是猜错了 哈哈
为啥子没变呢 是因为最后一步的async await 没有下一个中间件了啊 它是最后一个,现在我们把打印时间的async await 去掉试下 应该不会走渲染了
打印的结果跟我们猜测的一致
很好奇 ctx上下文里面都有什么
{
request: {
method: 'GET',
url: '/',
header: {
host: 'localhost:3000',
connection: 'keep-alive',
pragma: 'no-cache',
'cache-control': 'no-cache',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Mobile Safari/537.36',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'sec-fetch-site': 'none',
'sec-fetch-mode': 'navigate',
'sec-fetch-user': '?1',
'sec-fetch-dest': 'document',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'zh-CN,zh;q=0.9',
cookie: 'mba_muid=15865240722841357904765; __jda=111872281.15865240722841357904765.1586524072.1586532408.1586681425.4'
}
},
response: {
status: 404,
message: 'Not Found',
header: [Object: null prototype] {}
},
app: { subdomainOffset: 2, proxy: false, env: 'development' },
originalUrl: '/',
req: '<original node req>',
res: '<original node res>',
socket: '<original node socket>'
}
ctx.url == ctx.request.url