🌰举几个栗子,用Koa两天入门Node.js后端开发(一)

3,611 阅读5分钟

「这是我参与2022首次更文挑战的第1天,活动详情查看:2022首次更文挑战」。

前言

选用Koa作为web框架,用三篇文章讲解Node.js编写接口、服务端渲染(SSR)和MySQL数据库

🚩学习目标

用Koa一共实现5个GETPOST请求

  1. GET请求-返回文本
  2. GET请求-返回JSON
  3. GET请求-带参数
  4. GET请求-路由传参
  5. POST请求-带参数

Koa是什么?

Koa是基于Node.js实现的web框架。是一款轻量的框架,所有功能通过插件实现。

👉 koa中文网 www.koajs.com.cn

除Koa以外,Node.js的web框架还有很多,选择Koa的原因是学习路线简单,上手速度快

  • Express
  • Nest
  • Hapi
  • Egg(基于koa)

1. 准备工作

🚧Node.js 版本 >= 10

全局安装koa-generatorkoa2

npm install -g koa-generator koa2

koa-generator是Koa的脚手架,能快速生成项目结构。先了解一下怎么用

举个栗子🌰

  • 创建名为“vue-serve”的项目
koa2 vue-serve
  • 创建名为“vue-serve”的项目,使用ejs模板 和 sasscss编译
koa2 vue-serve -e -c sass

两个命令的创建结果对比(你就不要建两次了,看看就得嘞🤡)

image-20220123195729612.png

koa-generator其他参数

参数用途
-e使用ejs模板引擎(默认使用pug)ejs.bootcss.com
--hbs使用handlebars模板引擎www.handlebarsjs.cn
-H使用 hogan.js 模板引擎twitter.github.io/hogan.js
-n使用 nunjucks 模板引擎nunjucks.bootcss.com
-c指定 css编译器(less|stylus|compass|sass)(默认使用css)
-f强制目录不能为空

* 这里提到的模板引擎也是我们的服务端渲染的引擎

下面实践开始

2. 创建工程

新建项目 learn-Pug

koa2 learn-Pug

image-20220123173620257.png

初始化项目

cd learn-Pug && npm i

启动项目

npm run start

浏览器输入http://localhost:3000,出现Hello Koa2!表示项目运行成功

koa默认端口3000

image-20220123175449560.png

3. 解析过程

koa-generator生成好了路由和模板调用,我们只需要看routes和views两个文件夹。

image-20220123211608520.png

过程

  1. 根据访问的url去匹配路由
  2. 根据路由返回数据或使用Pug返回HTML
  3. 浏览器看到结果

流程.png

3.1 💥热更新

npm run start 启动后,修改代码只能重启koa才看到效果,我们改用dev,方便查看结果

npm run dev

如果出现报错

'.' 不是内部或外部命令,也不是可运行的程序
或批处理文件。
 ELIFECYCLE  Command failed with exit code 1.

package.json中的dev改成,再重新运行

"scripts": {
	"dev": "nodemon bin/www",
}

3.2 在Chrome中调试Node

package.json中添加一行运行debug

"scripts": {
	"debug": "nodemon --inspect bin/www",
}

启动调试

npm run debug
  1. 访问 localhost:3000 任意接口

  2. F12打开开发者工具

  3. element左边多了Node图标(如果没有,稍等一下或重新启动),点击进入新面板

image-20220125150040630.png

  1. 在Sources选项中打开调试的文件就可以了

image-20220125150353470.png

4. 请求

4.1 GET-返回文本

打开index.js,从第9行开始,找到这一段代码

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

访问loclhost:3000/string,看到koa2 string

image-20220125101219483.png

4.2 GET-返回JSON

打开index.js,从第13行开始,找到这一段代码

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

这次用工具请求loclhost:3000/json

我用Hoppscotch(原名postwoman)你也可以用其他请求工具,postman,apifox,apipost等

👉 GitHub

image-20220125102942197.png

4.3 GET-参数

index.js中新建一个带参数的get请求

// http://localhost:3000/get?size=100

router.get('/get', async (ctx, next) => {
  const { size } = ctx.query
  ctx.body = `您的size参数是${size}`
})

访问http://localhost:3000/get?size=100

image-20220125114632395.png

4.4 GET-路由传参

index.js中新建get请求

// http://localhost:3000/get/koa
router.get('/get/:id', async (ctx, next) => {
  const { id } = ctx.params
  ctx.body = `您的id参数是${id}`
})

image-20220125120503822.png

4.5 POST-参数

模板中没有post请求,在index.js中新建一个post请求

请求参数:nameid

router.post('/juejin', async (ctx, next) => {
  const { name, id } = ctx.request.body
  ctx.body = {
    name:`您的用户名是${name}`,
    id: `${id}`,
  }
})

用工具请求loclhost:3000/juejin

请求参数:

{
  "name":"Maokai",
  "id":1
}

看到结果

image-20220125110925308.png

4.6 其他请求

koa-router还支持putdelall请求,详细的看这里 👉Github

router
  .put('/juejin/:id', (ctx, next) => {
    // ...
  })
  .del('/juejin/:id', (ctx, next) => {
    // ...
  })
  .all('/juejin/:id', (ctx, next) => {
    // ...
  });

5. 子路由

了解完index.js后,打开users.js

子路由是为了避免所有路由写在一个文件,降低维护难度

第3行,表示该文件下的所有路由都有/users前缀

router.prefix('/users')

/ = /users

/bar = /users/bar

image-20220125165610981.png

引用子路由

定义完子路由以后要在app.js中添加引用,注意第9行和第36行

// ....
const index = require('./routes/index')
const users = require('./routes/users')
// ...
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())

新建路由文件后,在后面添加即可

6. next

前面一直没有讲请求中的next是干嘛的,涉及Koa的洋葱模型

image-20220126211833263.png

用来改变中间件的执行顺序

借用某CSDN博主的栗子 👉原文


const one = (ctx, next) => {
  console.log('👉 one');
  next();
  console.log('<< one');
}
 
const two = (ctx, next) => {
  console.log('👉 two');
  next();
  console.log('<< two');
}
 
const three = (ctx, next) => {
  console.log('👉 three');
  next();
  console.log('<< three');
}
 
app.use(one);
app.use(two);
app.use(three);
 
输出结果:
👉 one
👉 two
👉 three
<< three
<< two
<< one

最后

学会路由用法,就能给自己的vue,react项目写接口试试啦,而且是前后分离的哦~

👇👇👇下一篇讲服务端渲染

😜万水千山总是情,点个关注行不行~