koa2学习1--helloworld

1.在webstorm中新建一个项目koa2demo

将该项目初始化为node项目:(在终端输入)

npm init -y

初始化会生成一个package.json。

2.安装koa

npm install koa --save

在package.json中添加了koa的依赖。

3.HelloWorld

const Koa = require('koa');
const app = new Koa();


const main = async (ctx, next) => {
    // 设置response的Content-Type
    ctx.response.type = 'text/html';
    // 设置response的内容
    ctx.response.body = '<h1>Hello World!</h1>';
};

// 对于任何请求,该服务器程序都会调用main异步函数处理请求
app.use(main);

// 监听3000端口号
app.listen(3000);
console.log('app start at port 3000 ...');

4.一个例子

可以用以下3个middleware组成处理链,依次打印日志,记录处理时间,输出HTML:

async: 异步,await: async wait(异步等待)。

const Koa = require('koa');
const app = new Koa();

// 由async标记的函数称为异步函数,在异步函数中,可以用await调用另一个异步函数,这两个关键字在ES2017中引入。
// app.use() 注册异步(async)函数,并传入ctx和next参数。
// ctx包含request对象和response对象,next表示下一个异步函数。每个异步函数做一件事情。
// await next()调用下一个异步函数。await只能用在async函数中。
// 每个异步(async)函数都称为中间件(middleware)。这些async函数即中间件组成了一个处理链。
// app.use()中注册中间件的顺序决定了middleware的next顺序。
// 如果一个middleware没有调用await next(),那么后续注册的middleware将不再执行了。

// 打印url
app.use(async (ctx, next) => {
    console.log(`${ctx.request.method} ${ctx.request.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(`耗费时间:${ms}ms`);
});

// 处理请求
app.use(async (ctx, next) => {
    await next();
    ctx.response.type = 'text/html';
    ctx.response.body = '<h1>Hello World!</h1>';
});

app.listen(3000);
console.log('app start at port 3000 ...');

转载于:https://my.oschina.net/qiongleee/blog/1860506

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值