在cloudflare工作人员中使用aws4fetch包进行AWS api调用?

mad*_*uga 5 amazon-s3 aws-sdk aws-sdk-js cloudflare-workers

我无法使用 aws4fetch 调用 AWS Api。

有人能给我一个如何使用 cloudflare 工作人员调用 S3 putobject 的示例吗?

gij*_*joe 6

下面的代码帮助我将一个简单的txt文件从cloudflare工作人员上传到亚马逊S3存储桶

导入 aws4fetch

const aws4fetch = require('aws4fetch')
Run Code Online (Sandbox Code Playgroud)

声明您在 aws 中创建 iam 配置文件时保存的访问密钥和机密,该配置文件至少具有 putobject 和编程访问权限(通过仅将您感兴趣的 arn 存储桶作为资源传递来保护它)

const access_key = '<access_key_id_here>';
const access_secret = '<access_secret_here>';
const region = '<region>';
const bucket = '<bucket_name>';
Run Code Online (Sandbox Code Playgroud)

初始化 aws4fetch 客户端

const aws = new aws4fetch.AwsClient({
  accessKeyId:access_key,     
  secretAccessKey:access_secret
});
const endpoint = 'https://'+bucket+'.s3.'+region+'.amazonaws.com/';



addEventListener('fetch', function(event) {
    event.respondWith(handleRequest(event.request))
});

async function handleRequest(request) {
    const filename_key = 'test.txt';

    const content = `the content of the file`;

    const res = await aws.fetch(endpoint+filename_key, 
    { body: content, method: 'PUT'})

    return new Response('ok')

}
Run Code Online (Sandbox Code Playgroud)

请注意,您也可以使用 aws-sdk,这使得与 aws s3 交互更容易,但它会花费您至少 350kbytes 的额外代码(有 1mbyte 工作脚本的限制)