关于 wix-cli-backend-api
面向 Wix CLI 应用创建 HTTP 端点的技能,基于 Astro 路由,并说明文件路由、请求处理与发布流程。
主要功能
- 01基于 Astro 的 HTTP 端点
- 02文件系统自动发现路由
- 03动态路径参数
- 04HTTP 方法处理器
- 05请求与响应处理
- 06构建、预览和发布指引
适用场景
- 01为 Wix CLI 应用构建 REST API
- 02集成外部 API 或服务
- 03处理表单提交或文件上传
- 04从后端数据提供动态内容
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ wix/ skills --skill wix-cli-backend-api安装后在 Claude Code 中输入/wix-cli-backend-api确认已加载。
详细介绍
Wix 后端 API 构建器
为 Wix CLI 应用创建 HTTP 端点——用于处理 HTTP 请求、处理数据并返回响应的服务端路由。HTTP 端点由 Astro 端点提供支持,并会从文件系统中自动发现。
关键信息:
- 文件位于
src/pages/api/,扩展名为.ts - 无法通过
npm run generate添加——请直接创建文件 - 不会显示在应用控制面板的 Extensions 页面上
- 无需注册扩展(会自动发现)
- 替代 Wix CLI for Apps 旧版中的“HTTP 函数”
使用场景
在以下情况下使用 HTTP 端点:
- 构建支持多种 HTTP 方法的 REST API
- 与外部 API 或服务集成
- 处理复杂的表单提交或文件上传
- 提供动态内容(图片、RSS 源、个性化数据)
- 访问运行时数据或服务端数据库
文件结构和命名
基本端点
文件路径决定端点 URL:
src/pages/api/<your-endpoint-name>.ts
动态路由
使用方括号表示动态参数:
src/pages/api/users/[id].ts → /api/users/:id
src/pages/api/posts/[slug].ts → /api/posts/:slug
src/pages/api/users/[userId]/posts/[postId].ts → /api/users/:userId/posts/:postId
HTTP 方法
为每种 HTTP 方法导出具名函数。使用 astro 中的 APIRoute 进行类型标注。每个处理程序都会接收一个 request 对象并返回一个 Response:
import type { APIRoute } from "astro";
export const GET: APIRoute = async ({ request }) => {
console.log("Log from GET."); // This message logs to your CLI.
return new Response("Response from GET."); // This response is visible in the browser console
};
export const POST: APIRoute = async ({ request }) => {
const data = await request.json();
console.log("Log POST with body: ", data); // This message logs to your CLI.
return new Response(JSON.stringify(data)); // This response is visible in the browser console.
};
请求处理
路径参数
export const GET: APIRoute = async ({ params }) => {
const { id } = params; // From /api/users/[id]
if (!id) {
return new Response(JSON.stringify({ error: "ID required" }), {
status: 400,
statusText: "Bad Request",
headers: { "Content-Type": "application/json" },
});
}
// Use id to fetch data
};
查询参数
使用 new URL(request.url).searchParams:
export const GET: APIRoute = async ({ request }) => {
const url = new URL(request.url);
const search = url.searchParams.get("search");
const limit = parseInt(url.searchParams.get("limit") || "10", 10);
const offset = parseInt(url.searchParams.get("offset") || "0", 10);
// Use query parameters
};
请求正文
解析 POST/PUT/PATCH 请求中的 JSON 正文:
export const POST: APIRoute = async ({ request }) => {
try {
const body = await request.json();
const { title, content } = body;
if (!title || !content) {
return new Response(
JSON.stringify({ error: "Title and content required" }),
{
status: 400,
statusText: "Bad Request",
headers: { "Content-Type": "application/json" },
}
);
}
// Process data
} catch {
return new Response(JSON.stringify({ error: "Invalid JSON" }), {
status: 400,
statusText: "Bad Request",
headers: { "Content-Type": "application/json" },
});
}
};
标头
const authHeader = request.headers.get("Authorization");
const contentType = request.headers.get("Content-Type");
响应模式
始终返回带有适当状态码和标头的 Response 对象:
// 200 OK
return new Response(JSON.stringify({ data: result }), {
status: 200,
headers: { "Content-Type": "application/json" },
});
// 201 Created
return new Response(JSON.stringify({ id: newId, ...data }), {
status: 201,
headers: { "Content-Type": "application/json" },
});
// 204 No Content (for DELETE)
return new Response(null, { status: 204 });
// 400 Bad Request
return new Response(JSON.stringify({ error: "Invalid input" }), {
status: 400,
statusText: "Bad Request",
headers: { "Content-Type": "application/json" },
});
// 404 Not Found
return new Response(JSON.stringify({ error: "Not found" }), {
status: 404,
statusText: "Not Found",
headers: { "Content-Type": "application/json" },
});
// 500 Internal Server Error
return new Response(JSON.stringify({ error: "Internal server error" }), {
status: 500,
statusText: "Internal Server Error",
headers: { "Content-Type": "application/json" },
});
前端集成
在前端组件中使用 Wix 内置的 HTTP 客户端(httpClient.fetchWithAuth())调用 HTTP 端点:
import { httpClient } from "@wix/essentials";
// GET request
const baseApiUrl = new URL(import.meta.url).origin;
const res = await httpClient.fetchWithAuth(
`${baseApiUrl}/api/<your-endpoint-name>`,
);
const data = await res.text();
// POST request
const res = await httpClient.fetchWithAuth(
`${baseApiUrl}/api/<your-endpoint-name>`,
{
method: "POST",
body: JSON.stringify({ message: "Hello from frontend" }),
},
);
const data = await res.json();
构建、部署和删除
要将 HTTP 端点投入生产环境,请构建并发布项目:
发布后,端点即可通过生产环境 URL 访问并处理实时流量。
要删除 HTTP 端点,请移除 src/pages/api/ 下的文件,然后重新发布。
输出结构
src/pages/api/
├── users.ts # /api/users endpoint
├── users/
│ └── [id].ts # /api/users/:id endpoint
└── posts.ts # /api/posts endpoint
代码质量要求
- 使用严格的 TypeScript(不使用
any,明确指定返回类型) - 使用
astro中的APIRoute为所有处理程序标注类型 - 始终返回
Response对象,并对 JSON 使用JSON.stringify() - 使用恰当的 HTTP 状态码(200、201、204、400、404、500)
- 在 JSON 响应中包含
Content-Type: application/json标头 - 在错误响应中包含
statusText - 使用 try/catch 块处理错误
- 验证输入参数和请求正文
- 使用 async/await 处理异步操作
- 不使用
@ts-ignore注释
评论
支持 Markdown