vercel无服务函数

Vercel 支持无服务器函数(Serverless Functions),使用起来非常方便。以下是具体用法和配置说明:

1. 基本使用方式

无需配置的简单部署

直接在项目中创建 /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

2. 配置文件(可选但推荐)

创建 vercel.json 或修改现有配置:

{
  "functions": {
    "api/*.js": {
      "maxDuration": 10,  // 最大执行时间(秒)
      "memory": 1024      // 内存大小(MB)
    }
  },
  "rewrites": [
    {
      "source": "/api/:path*",
      "destination": "/api/:path*"
    }
  ]
}

3. 环境变量配置

在 Vercel 控制台或使用 CLI:

# 设置环境变量
vercel env add VARIABLE_NAME production

# 本地开发使用
vercel env pull .env.local

4. 本地开发

# 安装 Vercel CLI
npm i -g vercel

# 登录
vercel login

# 本地启动开发服务器
vercel dev

5. 高级特性

动态路由

api/
├── post/
│   ├── [id].js         → /api/post/:id
│   └── [id]/comment.js → /api/post/:id/comment

边缘函数(Edge Functions)

更快的全局响应,在 app 目录下使用:

// app/api/route.js (Next.js 13+)
export const runtime = 'edge';

export async function GET(request) {
  return new Response('Hello from Edge!');
}

6. 部署

# 部署到生产环境
vercel --prod

# 或通过 Git 自动部署(连接 GitHub/GitLab 等)

7. 限制和注意事项

  • 免费计划限制:

    • 函数执行时间:10秒(Hobby)、15秒(Pro)
    • 内存:1024MB
    • 请求数:100GB/月带宽
  • 文件大小限制: 50MB(包括依赖)

  • 支持语言: Node.js、Python、Go、Ruby

  • 冷启动: 不活跃的函数可能有冷启动延迟

8. 调试和监控

  • Vercel 控制台: 查看函数日志和性能
  • CLI 查看日志:
    vercel logs api/hello.js
    

最简单的开始方式是直接在项目中创建 api 目录并编写函数文件,Vercel 会自动处理其余部分。

9. 结合json-server

json-server 需要持久守护进程式的服务,但是Vercel(是无服务器架构)并不支持,但是我们可以借助于其(Vercel)的Serverless之区域函数解决。
其中 kitloong的json-server-vercel是一个利用此现成的解决方案。

posted @ 2026-01-06 23:59  丁少华  阅读(19)  评论(0)    收藏  举报