全书目录

第十三篇:Fastify 完全指南 —— 高速物流中枢宇宙

第四章:路由 —— 包裹先进入哪条分拣线

1 分钟 110 字 第 259 / 962 个阅读单元

Fastify 的路由就是中枢里的分拣入口。

js
import Fastify from 'fastify'

const fastify = Fastify({ logger: true })

fastify.get('/shipments', async function () {
  return [{ id: 'S1001' }, { id: 'S1002' }]
})

fastify.get('/shipments/:id', async function (request) {
  const { id } = request.params
  return { id, status: 'sorting' }
})

fastify.post('/shipments', async function (request, reply) {
  reply.code(201)
  return { created: true, shipmentId: 'S1003' }
})

你可以把它理解成:

text
高速物流中枢
├── GET  /shipments      -> 查所有包裹
├── GET  /shipments/:id  -> 查单个包裹
└── POST /shipments      -> 新建包裹运单

如果你想写完整配置,而不是只用快捷方法,可以写成 route

js
fastify.route({
  method: 'GET',
  url: '/shipments/:id',
  handler: async function (request) {
    return { id: request.params.id }
  }
})

route 的好处是:后面你要挂 schema、局部 hooksconfig,都更集中。