micro-router 异步编程指南:如何用 async/await 编写强大的异步路由处理器
【免费下载链接】micro-router:station: A tiny and functional router for Zeit's Micro项目地址: https://gitcode.com/gh_mirrors/mi/micro-router
Micro-router 是专为 ZEIT's Micro 服务端框架打造的一款轻量级异步路由库,它天生为async/await设计,让你几行代码就能写出强大的异步路由处理器。本文面向新手,带你快速掌握用 micro-router 编写异步 API 路由的完整流程。
什么是 micro-router?超轻量级路由库的核心特性
micro-router(包名microrouter)是一个功能完整但体积极小的路由工具,主要特性有:
- 🪶超轻量:核心逻辑只有几十行代码,零学习成本
- 📐函数式:每个 HTTP 方法(
get、post、put等)都是一个函数 - ⚡原生异步:内部使用
async/await驱动路由匹配,天然支持异步处理器
核心源码位于src/lib/index.js,你甚至可以直接读懂它的全部实现。
一键安装步骤:30 秒上手 micro-router
方式一:直接作为项目依赖安装(推荐):
$ yarn add microrouter方式二:克隆源码研究:
$ git clone https://gitcode.com/gh_mirrors/mi/micro-router $ cd micro-router $ yarn install如何用 async/await 编写第一个异步路由处理器
micro-router 的处理器(handler)就是一个普通的(req, res) => {}函数,它可以是任意异步函数——这正是它的设计初衷。
const { send } = require('micro') const { router, get } = require('microrouter') // 处理器是 async 函数,可自由使用 await const hello = async (req, res) => { const name = await fetchUserName(req.params.who) // 异步取数据 send(res, 200, `Hello ${name}`) } module.exports = router(get('/hello/:who', hello))send是 micro 框架提供的响应方法。整个服务就这一行module.exports,即可运行在 Micro 的 Serverless 环境中。
路由参数与查询参数:req.params 和 req.query 用法
在路由路径中用:定义参数(如/hello/:who),请求/hello/World后,处理器内即可通过req.params取到{ who: 'World' };URL 中的查询字符串则通过req.query获取:
// GET /hello/world?time=now const routes = router( get('/hello/:msg', (req) => `Hello ${req.params.msg} ${req.query.time}`) )参数与查询的解析逻辑在src/utils/index.js的getParamsAndQuery函数中,它借助url-pattern包完成路径匹配。
路由匹配内幕:findRoute 如何用 await 遍历路由
理解异步的关键在于源码中的findRoute函数(src/lib/index.js第 24-31 行):
const findRoute = (funcs, namespace = '') => async (req, res) => { for (const fn of funcs) { const result = await fn(req, res, namespace) if (result || res.headersSent) return result } return null }它按顺序await每一条路由,只要某条路由有返回值或已发送响应头,立即停止匹配。这带来两个实用结论:
- 路由顺序很重要:把具体路径放在通配路由之前,例如
/path要在/:param之前声明 - 处理器同步或异步均可:
await对非 Promise 值同样有效,所以同步函数照常工作
相关行为在src/lib/index.test.js中有完整测试覆盖,比如 "async handlers" 与 "multiple matching async routes" 两个用例。
4 个编写异步处理器的实用技巧
1. 解析请求体要用 micro 的 json 方法
micro-router 本身不解析 body,异步场景下这样写最自然:
const user = async (req, res) => { const body = await json(req) // 异步解析请求体 send(res, 200, body) }2. 用 withNamespace 组织版本化 API
const oldApi = withNamespace('/api/v1') const newApi = withNamespace('/api/v2') module.exports = router( oldApi(get('/', async (req, res) => send(res, 200, 'v1'))), newApi(get('/', async (req, res) => send(res, 200, 'v2'))) )3. 捕获异步异常,返回友好错误
const safe = (handler) => async (req, res) => { try { await handler(req, res) } catch (err) { send(res, 500, 'Internal Error') } }4. 用/*兜底处理未匹配路由
const notFound = (req, res) => send(res, 404, 'Not found route') module.exports = router(get('/hello/:who', hello), get('/*', notFound))常见问题 FAQ
Q:micro-router 和 Express 路由有什么区别?A:它专为 Serverless 场景设计,不维护应用实例,每个请求独立处理,体积更小,天然适配 micro 的部署方式。
Q:支持哪些 HTTP 方法?A:get、post、put、patch、del、head、options全部支持,见src/lib/index.js第 4 行的方法定义。
Q:路径匹配支持正则吗?A:支持。传入url-pattern的UrlPattern实例即可用正则匹配,但此时不能配合命名空间使用。
小结
micro-router 用最小的代码量实现了完整的异步路由能力:router负责编排,get/post等函数定义路由,处理器中自由使用async/await对接数据库、外部 API 等异步资源。如果你正在为 Serverless 服务搭建 API,这是一个简单、快速且免费的优秀选择。
【免费下载链接】micro-router:station: A tiny and functional router for Zeit's Micro项目地址: https://gitcode.com/gh_mirrors/mi/micro-router
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考