You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cloudflare Worker生成R2预签名URL返回空对象求助

Cloudflare R2预签名URL返回空对象的解决方法
  • 必须提供有效R2凭证
    仅在Cloudflare Worker/Pages Functions环境中,R2客户端可自动获取凭证。如果是本地Node.js或其他非Cloudflare运行时环境,必须传入从Cloudflare控制台生成的R2 Access Key ID和Secret Access Key,不能留空字符串。

  • 修正r2.sign的返回值处理
    r2.sign方法返回的是Request实例,直接将其转为JSON会得到空对象(因为Request的核心属性不可枚举)。正确做法是提取Request.url属性,这才是生成好的预签名URL。

  • 调整过期时间的配置位置
    过期时间参数X-Amz-Expires应配置在aws选项中,而非请求headers里,官方规范中该参数是签名查询参数的一部分。

  • 验证Bucket URL的正确性
    确保bucketNameToUrl映射的URL格式正确:https://<账号ID>.r2.cloudflarestorage.com/<桶名>,检查账号ID、桶名是否与控制台一致,无拼写错误。


修正后的代码示例:

// 非Worker环境需填入真实的R2凭证
const r2 = new AwsClient({
  accessKeyId: "你的R2 Access Key ID",
  secretAccessKey: "你的R2 Secret Access Key",
  service: "s3",
  region: "auto",
});

app.get("/getUploadUrl", async (c) => {
  const timeOut = +c.req.queries("timeOut") ?? 60 * 5;
  const fileName = c.req.queries("fileName") ?? crypto.randomUUID();
  const bucketName = c.req.header("bucket");
  const bucketUrl = bucketNameToUrl[bucketName];
  
  if (!bucketUrl) {
    return c.json({ error: "无效的桶名称" }, 400);
  }

  const signedRequest = await r2.sign(
    new Request(`${bucketUrl}/${fileName}`, {
      method: "PUT",
    }),
    {
      aws: { 
        signQuery: true,
        expires: timeOut
      },
    }
  );
  
  return c.json({ signedUrl: signedRequest.url });
});

内容的提问来源于stack exchange,提问作者harpy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 04:45:35