Node.js的web框架koa2入门

koa入门

创建koa2工程

首先,我们创建一个目录hello-koa并作为工程目录用VS Code打开。然后,我们创建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 = '

Hello, koa2!

'; }); // 在端口3000监听: app.listen(3000); console.log('app started at port 3000...'

对于每一个http请求,koa将调用我们传入的异步函数来处理:

async (ctx, next) => {
    await next();
    // 设置response的Content-Type:
    ctx.response.type = 'text/html';
    // 设置response的内容:
    ctx.response.body = '

Hello, koa2!

'; }

其中,参数ct

你可能感兴趣的:(nodejs教程,前端,node.js,javascript)