跳到主要内容
NODE.JS

Node.js 接入视频生成 API

示例代码在 Node.js 服务端运行。API Key 从环境变量读取,不发送到浏览器,也不写入任务输出。

最后更新

完整示例

create-and-wait.jsjs
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
}

接入检查

  1. 确认 VIDEO_API_BASE 与 VIDEO_API_KEY 只存在于服务端环境。
  2. 使用 /v1/models 验证当前 Key 的可用模型。
  3. 为每次业务提交生成 UUID 作为幂等键。
  4. 每 3 至 5 秒轮询,直到 completed 或 failed。
  5. 下载并保存 metadata.url 指向的视频;不要把直链当作永久存储。
任务状态与错误
查看轮询之外的幂等、限流和返回码处理。
API 总览
返回请求字段、模式和安全说明。