【复盘】Koa 项目基本搭建(一)

330 阅读3分钟

一、项目初始化

PNPM 初始化

pnpm init

生成 packages.json 文件

  • 记录项目依赖

Git 初始化

git init

生成 .git 隐藏文件夹

创建 README.md

用来记录项目开发过程

二、项目基础搭建

1. 安装 Koa 框架

pnpm add koa

根目录下创建 src 文件夹,创建 main.js 入口文件

2.编写最简单的 Koa 应用程序

服务代码

// main.js
// node ./src/main.js 启动服务
const Koa = require('koa');
const app = new Koa();

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

app.listen(3000);

在 Koa 中,中间件(middleware)是一种处理 HTTP 请求的方式,每个中间件都可以对请求和响应进行一些处理。中间件在 Koa 中是一个函数,它接收一个 context 对象和一个 next 函数作为参数。

app.use 方法用于注册中间件。

每个中间件都是一个异步函数,接收 ctx(上下文)和 next(下一个中间件的引用)作为参数。

中间件的执行顺序与它们注册的顺序一致。

next 函数用于调用下一个中间件。如果一个中间件不调用 next,后续的中间件将不会被执行,从而中断请求的处理。

Koa 的中间件机制使得请求的处理可以通过一系列的中间件函数依次执行,每个中间件可以负责特定的任务,使代码结构更加清晰和可维护。

启动项目

node ./src/main.js 最原始的方式启动

浏览器访问 localhost: 3000 访问

image-20231203171307181

如何实时监听项目变化并重新启动?(很久没写nodejs代码了,忘了,问完这个问题想起来了有个 nodemon,使用nodemon启动项目。)

  • nodemon

实时监听文件变更,热更新。

三、项目基本配置优化

1. 自动重启服务(热更新)

安装 nodemon 工具

pnpm add nodemon

编写启动脚本

package.json > scripts

"scripts":{
  "dev":"nodemon ./src/main.js"
}

nodemon 配置细节

2. 配置文件

推荐工具 dotenv

在根目录加载一个.env的文件,将这个文件里面的键值对写到环境变量中 process.env

dotenv 安装

pnpm add dotenv

根目录下创建 .env 文件

APP_PORT=8000
DB_HOST=localhost
DB_PASSWORD=123456

创建 src/config/config.default.js 文件管理环境变量

// src/config/config.default.js
const dotenv = require("dotenv")


dotenv.config()

console.log(process.env.APP_PORT);
console.log(process.env.DB_HOST);
console.log(process.env.DB_PASSWORD);

module.exports = process.env

在 main.js 使用 环境变量

// 加载 Koa框架
const Koa = require('koa');
// 获取环境变量
const {APP_PORT} = require("./config/config.default")

// Koa 框架实例化
const app = new Koa();

// 中间件 app.use
// 两个参数 ctx,next
app.use(async (ctx,next) => {
    ctx.body = 'Hello World!';
});

app.listen(APP_PORT,()=>{
    console.log(`server is running on http://localhost:${APP_PORT}`)
}); // 监听 3000 端口

重启服务后

image-20231203173250233

四、添加路由

在 Koa 中,路由(routing)用于确定应用程序如何响应客户端的请求。与 Express 不同,Koa本身并没有内置路由功能,但是开发者可以使用第三方的中间件来实现路由。

一个常用的 Koa 路由中间件是 koa-router,它可以方便地用于定义路由。首先,你需要安装 koa-router

官方使用文档:github.com/koajs/route…

安装 @koa/router

pnpm add @koa/router 

koa-route 和 @koa/router 的区别?

@koa/router 是 Koa 官方推荐的新版本,而 koa-router 是旧版本 在 Koa 中,koa-router@koa/router 都是用于处理路由的库,但它们是不同的版本,@koa/router 是 Koa 官方推荐的新版本,而 koa-router 是旧版本。以下是它们的主要区别:

  1. 支持的 Koa 版本:

    • koa-router: 是 Koa 1.x 版本的路由库,主要用于旧版本的 Koa 框架。
    • @koa/router: 是 Koa 2 及更新版本的官方推荐路由库,支持最新的 Koa 版本。
  2. 模块化设计:

    • koa-router: 在使用时需要先引入整个模块,然后创建实例进行路由的配置。
    • @koa/router: 设计更为模块化,可以直接引入需要的功能模块,提供了更灵活的使用方式。
  3. 语法和特性:

    • koa-router: 使用相对简单的 API,主要包括 router.get(), router.post(), 等等,以及中间件的使用。
    • @koa/router: 提供了更多功能,例如路由前缀、参数校验、路由嵌套等,使得它更适合于中大型应用或者需要更复杂路由配置的场景。
  4. 异步/同步支持:

    • @koa/router: 由于 Koa 2 及更新版本天生支持 async/await,因此 @koa/router 的 API 函数都是基于异步的。这有助于处理异步操作,例如数据库查询等。
    • koa-router: 虽然也可以在 Koa 2 中使用,但它的 API 设计较旧,主要是基于回调函数的方式,与 Koa 2 的异步风格有些不同。

@koa/router 中间件的简单使用

后期可以通过一篇文章来总结 koa-router 各种使用方法

// 加载 Koa框架
const Koa = require('koa');
// 加载 @koa/router 路由中间件
const Router = require('@koa/router');

// 获取环境变量
const {APP_PORT} = require("./config/config.default")

// Koa 框架实例化
const app = new Koa();
// 实例化路由中间件
const router = new Router()

// // 定义路由
router.get('/', (ctx, next) => {
    ctx.body = 'Home Page';
});
router.get('/user', (ctx, next) => {
    ctx.body = 'User Page';
});
// 使用 app.use(router.routes()) 将路由中间件注册到应用中
// 当请求到达时,中间件将根据请求的路径选择匹配的路由进行处理。
// router.routes() 是用于返回一个中间件函数,该函数将处理路由匹配和调用相应的处理函数。
// 如果你想要处理不匹配的情况,可以使用 router.allowedMethods():
// 这样可以处理请求方法不允许的情况,返回适当的 HTTP 状态码。

// 将路由中间件注册到应用
app.use(router.routes());
app.use(router.allowedMethods());

app.listen(APP_PORT,()=>{
    console.log(`server is running on http://localhost:${APP_PORT}`)
}); // 监听 3000 端口


// 换服务端语言请问自己问什么要换?当前语言有什么缺陷!

PS:中间件使用步骤

  1. 导入包
  2. 实例化对象
  3. 编写路由
  4. 注册中间件

router.routes() 是用于返回一个中间件函数,该函数将处理路由匹配和调用相应的处理函数。

app.use 不能直接使用 router~。

访问 / 根路由

image-20231203183922684

访问 /user 路由

image-20231203184424578

优化项

优化项1:路由文件拆分

所有的路由放在一个文件里,开发体验会非常的不友好,查询也不方便,所以要做一个路由文件的拆分。

解决方案:单独抽离出 Route 层

单独抽离出 Route 层

在 src 文件夹下新建 router (controller/routes) 文件夹

抽离用户接口

在 ./src/router 文件夹下新建 user.route.js 用来管理 user 模块相关接口。

PS:user.route.js 为 个人命名习惯。

const Router = require('@koa/router')

// Router 实例化
// prefix 添加接口前缀
// 在之后的 router 接口都会拼接上 prefix
const router = new Router({
    prefix: '/users'
})

// GET /users/
router.get('/',(ctx,next)=>{
    ctx.body = 'hello users'
})

module.exports = router
在 main.js 导入 路由
// 加载 Koa框架
const Koa = require('koa');

// 获取环境变量
const {APP_PORT} = require("./config/config.default")

// 导入 users 路由
const userRouter = require("./router/user.route")

// Koa 框架实例化
const app = new Koa();

app.use(userRouter.routes());

app.listen(APP_PORT,()=>{
    console.log(`server is running on http://localhost:${APP_PORT}`)
}); // 监听 3000 端口


// 换服务端语言请问自己问什么要换?当前语言有什么缺陷!
访问 / users

image-20231203185328308