You need to enable JavaScript to run this app.
全站加速

全站加速

复制全文
AI Pages 开发指南
Functions
复制全文
Functions

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!" });
}

第二步

  1. 安装 iga pages cli,npm install -g @iga-pages/cli

  2. 在项目根路径下执行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.jsexample.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匹配

Function Handlers

// api/hello.js
export default async function handler(request, response) {
  response.json({ message: `Hello, IGA!` });
}

handler 函数中的 request 和 response 对象基于 Node.js HTTP RequestResponse 标准做了一些扩展,具体扩展如下:

属性说明
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()
最近更新时间:2026.03.20 09:35:06
这个页面对您有帮助吗?
有用
有用
无用
无用