基于Koa+TS开发后端接口(二)添加路由

1 引言

关键词:TypeScript Node Koa API Koa-Router Router

基于上一篇新建项目的文章,我们在此基础上添加路由,定义Api接口,提供给前端访问。

前提:阅读本文章之前,我们假设

  1. 你已经对TypeScript、Yarn(或者Npm)、NodeJS、Router等基本概念有一定的了解。
  2. 你已经阅读了上一篇文章:《基于 Koa + TS 开发后端服务接口(一)新建项目》

2 系列文章

  • 基于 Koa + TS 开发后端接口(一)新建项目
  • 基于 Koa + TS 开发后端接口(二)添加路由
  • 基于 Koa + TS 开发后端接口(三)ORM

3 新增依赖

yarn add koa-router
yarn add -D @types/koa-router
1
2

4 新建路由

新建文件夹:src/controller
新建文件:src/controller/index.ts

// src/controller/index.ts

import Router from "koa-router"

const router = new Router({
  prefix: "/"
})

router.get("/", async (ctx) => {
  ctx.type = "application/json"
  ctx.body = "{'key':'1','name':'index'}"
})

router.post("/getName1", async (ctx) => {
  ctx.type = "application/json"
  ctx.body = "{'key':'1','name':'zhangsan'}"
})

export default router
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

5 改造入口文件

// src/index.ts

import Koa from 'koa'
// 引入Index路由
import index from "./controller/index"

const server: Koa = new Koa()
const port: number = 3000
// 演示的代码不要了
// server.use((ctx: Koa.DefaultContext) => {
//     ctx.body = 'hi koa'
// })

// 使用Index路由中间件
server.use(index.routes()).use(index.allowedMethods())

server.listen(port, () => {
    console.log(`Node.js v${process.versions.node} : http://localhost:3000`)
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

6 运行效果

打开浏览器输入上面启动后的地址查看结果。

第一个/是get请求,能正常请求数据,第二个定义的是post请求,使用get访问会报错405。

Get
Post

注:post请求可使用PostApi或者Postman等工具进行测试