Node.js 接入视频生成 API
示例代码在 Node.js 服务端运行。API Key 从环境变量读取,不发送到浏览器,也不写入任务输出。
完整示例
const baseUrl = process.env.VIDEO_API_BASE
const apiKey = process.env.VIDEO_API_KEY
async function call(path, init = {}) {
const response = await fetch(`${baseUrl}${path}`, {
...init,
headers: {
Authorization: `Bearer ${apiKey}`,
Accept: 'application/json',
...(init.body ? { 'Content-Type': 'application/json' } : {}),
...init.headers,
},
})
const body = await response.json()
if (!response.ok || body.error) {
throw new Error(JSON.stringify(body))
}
return body
}
export async function createAndWait() {
let task = await call('/v1/videos', {
method: 'POST',
headers: { 'Idempotency-Key': crypto.randomUUID() },
body: JSON.stringify({
model: 'seedance2.0',
prompt: '一只橘猫坐在窗台上看雨,镜头缓慢推近',
seconds: 5,
resolution: '720p',
aspect_ratio: '16:9',
}),
})
while (task.status !== 'completed' && task.status !== 'failed') {
await new Promise((resolve) => setTimeout(resolve, 4000))
task = await call(`/v1/videos/${task.id}`)
}
if (task.status === 'failed') {
throw new Error(task.error?.message || 'video generation failed')
}
return task
}接入检查
- 确认 VIDEO_API_BASE 与 VIDEO_API_KEY 只存在于服务端环境。
- 使用 /v1/models 验证当前 Key 的可用模型。
- 为每次业务提交生成 UUID 作为幂等键。
- 每 3 至 5 秒轮询,直到 completed 或 failed。
- 下载并保存 metadata.url 指向的视频;不要把直链当作永久存储。
不要在前端暴露 Key
此示例只适用于 Node.js 服务端。浏览器端调用会向用户暴露模型 API Key,不能作为生产接入方案。