简体   繁体   English

如何使用@aws-sdk/client-s3 设置自定义 header?

[英]How to set a custom header using @aws-sdk/client-s3?

Cloudflare's R2 has an extension that prevents a NoSuchBucket error, by creating the bucket if it does not exist. Cloudflare 的 R2 有一个扩展,可以防止NoSuchBucket错误,如果它不存在则创建存储桶。 To enable it, you're supposed to add a cf-create-bucket-if-missing : true header on the PutObject request.要启用它,您应该在PutObject请求上添加一个cf-create-bucket-if-missing : true header。 Can this header be set if we're using the @aws-sdk/client-s3 npm package?如果我们使用@aws-sdk/client-s3 npm package,可以设置这个 header 吗? If so, how?如果是这样,怎么做?

If the answer is no, is there an alternative workaround that you would recommend?如果答案是否定的,是否有您推荐的替代解决方法?

If it helps, I'm creating a backend nestjs API, and would like to include this header in outgoing requests.如果有帮助,我正在创建一个后端nestjs API,并希望在传出请求中包含这个header。

The AWS SDK v2 allows you to modify requests via Middleware . AWS SDK v2 允许您通过Middleware修改请求。

Here's an example of adding a custom header using middleware:下面是使用中间件添加自定义 header 的示例:

const client = new S3({ region: "us-east-1" });

client.middlewareStack.add(
  (next, context) => (args) => {
    args.request.headers["cf-create-bucket-if-missing"] = "true";
    return next(args);
  },
  {
    step: "serialize",
  }
);

const params = {}; // TODO: fill in usual PutObject params

await client.PutObject(params);

There's a good article that dives into the middleware stack here . 这里有一篇深入探讨中间件堆栈的好文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM