
























Vercel 支持无服务器函数(Serverless Functions),使用起来非常方便。以下是具体用法和配置说明:
直接在项目中创建 /api 目录,每个 .js、.ts、.py、.go 文件都会自动成为一个 API 端点:
项目结构:
├── api/
│ ├── hello.js → /api/hello
│ └── user/[id].js → /api/user/:id (动态路由)
└── 其他文件
JavaScript/TypeScript:
// api/hello.js
export default function handler(req, res) {
res.status(200).json({ message: 'Hello World' });
}
Python:
# api/hello.py
from http.server import BaseHTTPRequestHandler
class handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write(b'Hello World')
return
创建 vercel.json 或修改现有配置:
{
"functions": {
"api/*.js": {
"maxDuration": 10, // 最大执行时间(秒)
"memory": 1024 // 内存大小(MB)
}
},
"rewrites": [
{
"source": "/api/:path*",
"destination": "/api/:path*"
}
]
}
在 Vercel 控制台或使用 CLI:
# 设置环境变量
vercel env add VARIABLE_NAME production
# 本地开发使用
vercel env pull .env.local
# 安装 Vercel CLI
npm i -g vercel
# 登录
vercel login
# 本地启动开发服务器
vercel dev
api/
├── post/
│ ├── [id].js → /api/post/:id
│ └── [id]/comment.js → /api/post/:id/comment
更快的全局响应,在 app 目录下使用:
// app/api/route.js (Next.js 13+)
export const runtime = 'edge';
export async function GET(request) {
return new Response('Hello from Edge!');
}
# 部署到生产环境
vercel --prod
# 或通过 Git 自动部署(连接 GitHub/GitLab 等)
免费计划限制:
文件大小限制: 50MB(包括依赖)
支持语言: Node.js、Python、Go、Ruby
冷启动: 不活跃的函数可能有冷启动延迟
vercel logs api/hello.js
最简单的开始方式是直接在项目中创建 api 目录并编写函数文件,Vercel 会自动处理其余部分。
json-server 需要持久守护进程式的服务,但是Vercel(是无服务器架构)并不支持,但是我们可以借助于其(Vercel)的Serverless之区域函数解决。
其中 kitloong的json-server-vercel是一个利用此现成的解决方案。
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。