基于koa2搭建一个node应用实践

1,219 阅读2分钟

基于koa2搭建一个node应用实践

正儿八经的前端开发迈出全栈的第一步,记录一次用 koa2 搭建一个后台应用。

环境搭建

前期已安装好

  • node v10.16.0
  • npm 6.9.0

项目准备

# 创建项目文件夹
mkdir node-koa2-app

# 进入文件夹
cd node-koa2-app

# npm 初始化
npm init -y

初体验koa服务

安装koa框架

npm i koa -S

创建 app.js 文件,尝试下 Hello World!

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

app.use(async ctx => {
    ctx.body = 'Hello World!';
});

app.listen(3000);

访问 http://localhost:3000 就能看到 Hello World! 了,真是简单。

再次优化一下,访问是一个完成的 html

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

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

app.listen(3000, () => {
    console.log('listening server http://localhost:3000');
});
app.listen(3001, () => {
    console.log('listening server http://localhost:3001');
});

中间件

Koa 应用程序是一个包含一组中间件函数的对象,它是按照类似堆栈的方式组织和执行的。

ctx

ctx就是上下文(Context),Context 将 node 的 request 和 response 对象封装到单个对象中,还对 Koa 内部对一些常用的属性或者方法做了代理操作,使得我们可以直接通过 ctx 获取。比如,ctx.request.url 可以写成 ctx.url。除此之外,Koa 还约定了一个中间件的存储空间 ctx.state。通过 state 可以存储一些数据,比如用户数据,版本信息等。

next

这是一种级联的方式,当一个中间件调用 next() 则该函数暂停并将控制传递给定义的下一个中间件。当在下游没有更多的中间件执行后,堆栈将展开并且每个中间件恢复执行其上游行为。

// 按照官方示例
const Koa = require('koa')
const app = new Koa()

// 记录执行的时间
app.use(async (ctx, next) => {
  let stime = new Date().getTime()
  console.log('开始时间'+stime);
  await next()
  let etime = new Date().getTime()
  ctx.response.type = 'text/html'
  ctx.response.body = '<h1>Hello World!</h1>'
  console.log('结束时间'+etime);
  console.log(`请求地址: ${ctx.path},响应时间:${etime - stime}ms`)
});

app.use(async (ctx, next) => {
  console.log('中间件1 doSoming');
  await next();
  console.log('中间件1 end');
})

app.use(async (ctx, next) => {
  console.log('中间件2 doSoming');
  await next();
  console.log('中间件2 end');
})

app.use(async (ctx, next) => {
  console.log('中间件3 doSoming');
  await next();
  console.log('中间件3 end');
})

app.listen(3000, () => {
  console.log('server is running at http://localhost:3000')
})

路由koa-router

引入koa-router

npm i koa-router -S

安装完成后执行

const Koa = require('koa')
// 注意 require('koa-router') 返回的是函数:
const router = require('koa-router')()
const app = new Koa()

// 添加路由
 router.get('/', async (ctx, next) => {
    ctx.response.body = `<h1>index page</h1>`
})

router.get('/home', async (ctx, next) => {
    ctx.response.body = '<h1>HOME page</h1>'
})

router.get('/404', async (ctx, next) => {
    ctx.response.body = '<h1>404 Not Found</h1>'
})

// 调用路由中间件
app.use(router.routes())

app.listen(3000, ()=>{
  console.log('server is running at http://localhost:3000')
})

这样就能实现一个网站应用了,对于前端开发者来说,node 有天然的优势,js语法相当友好,当然肯定也会因为弱语言类型少不了坑,后面一步一步学习。