AI Pages 提供基于文件系统的 Node.js Serverless Functions 能力。在项目根目录创建 api/ 目录,其中每个 .js 文件自动映射为一条可访问的 HTTP 路由,无需任何额外配置。
第一步:在项目根目录创建 api/hello.js:
export async function GET(request) { return Response.json({ message: "Hello from IGA Pages!" }); }
第二步:
安装 iga pages cli,npm install -g @iga-pages/cli
在项目根路径下执行iga pages dev开发服务器,访问 http://localhost:3000/api/hello。
api/ 目录结构直接映射为 URL 路径,支持三种路由类型
api/ ├── index.js → /api (静态路由) ├── hello.js → /api/hello (静态路由) ├── users/ │ ├── list.js → /api/users/list (静态路由) │ └── [id].js → /api/users/:id (动态路由) ├── [id].js → /api/:id (动态路由) ├── group/ │ └── [id]/ │ └── detail.js → /api/group/:id/detail (动态路由) └── [[default]].js → /api/:default* (Catch-all)
说明:
路由尾部斜杠 / 是可选。
/api/hello和/api/hello/将被路由到/api/hello.js。模糊匹配时 [id] 必填。
/api/123会匹配到/api/[id].js,/api/不会匹配到。通用匹配 [[default]] 可匹配任意路径。
/api/和/api/222会匹配到/api/[[default]].js。
上述文件系统生成的路由规则是:
| 文件路径 | 访问路径 | 是否匹配 |
|---|---|---|
| /api/index.js | example.com/api | 匹配 |
| example.com/api/ | 匹配 | |
/api/hello.js | example.com/api/hello | 匹配 |
| example.com/api/hello2 | 不匹配 | |
/api/users/list.js | example.com/api/users/list | 匹配 |
/api/users/[id].js | example.com/api/users/22 | 匹配 |
| example.com/api/users/22/ | 匹配 | |
| example.com/api/users/ | 不匹配 | |
/api/[id].js | example.com/api/ | 不匹配 |
| example.com/api/1212 | 匹配 | |
/api/group/[id]/detail.js | example.com/api/group/12/detail | 匹配 |
| example.com/api/group//detail | 不匹配 | |
/api/[[default]].js | example.com/api/ | 匹配 |
| example.com/api/2232 | 匹配 |
// api/hello.js export default async function handler(request, response) { response.json({ message: `Hello, IGA!` }); }
handler 函数中的 request 和 response 对象基于 Node.js HTTP Request 和 Response 标准做了一些扩展,具体扩展如下:
| 属性 | 说明 |
|---|---|
request.query | 获取 URL 查询参数,同名多参数自动转为数组 |
request.params | 获取动态路由参数,如 api/users/[id].js 中可获取 { id: "123" } |
request.cookies | 获取请求携带的 Cookie 数据,如 { token: "abc" },无 Cookie 时为 {} |
request.body | 自动解析请求体数据(根据请求 Content-Type 自动处理),无请求体时为 undefined |
response.status(code) | 设置 HTTP 响应状态码,支持链式调用 |
response.json(data) | 返回 JSON 格式响应,自动设置 Content-Type: application/json |
response.send(data) | 返回通用响应,根据数据类型自动匹配 Content-Type |
response.redirect(url) | 页面 / 接口重定向,默认使用 307 临时重定向状态码 |
response.redirect(status, url) | 自定义状态码重定向,如 res.redirect(301, '/new-path') |
Function 支持 Express/Koa 第三方 Node 框架,使用 Express/Koa 开发时需注意,框架的路由只需要集中在一个函数文件里面处理,无需额外启动 HTTP Server 且需导出框架的实例
// api/[[default]].js import express from "express"; const app = express(); app.use(express.json()); // 路由路径基于文件系统位置,对应路由为/api/users app.get("/users", (req, res) => res.json({ users: [] })); app.post("/users", (req, res) => res.status(201).json({ user: req.body })); export default app; // 不要调用 app.listen()