aws s3 curl PUT 可以工作,但在 JavaScript 中获取却不行

问题描述 投票:0回答:1

这个问题已被问过很多次,但答案始终是“在标头中包含 Content-Type”。我已经用不同的值做了很多次,但没有成功。 我正在尝试上传图片。

这是我的代码:

const res = await fetch(preSignedUrl, {
        method: 'PUT',
        headers: {
          'Content-Type': mimetype,
        },
        body: file
      });

预签名网址来自我的后端:

static async createPreSignedUrl(key: string | undefined, mimetype: string | undefined): Promise<string> {
    if (!key || !mimetype) {
      throw new Error(`Cannot create a pre-signed url without a key or a mimetype`);
    }
    const client = new S3Client({
      credentials: {
        accessKeyId: String(process.env.AWS_S3_ACCESS_KEY_ID),
        secretAccessKey: String(process.env.AWS_S3_SECRET_ACCESS_KEY),
      },
      region: String(process.env.AWS_S3_REGION),
    });
    const command = new PutObjectCommand({
      Bucket: String(process.env.AWS_S3_ASSETS_BUCKET_NAME),
      Key: key,
      ContentType: mimetype
    });
    return getSignedUrl(client, command, {
      expiresIn: 3600
    });
  }

我不认为预签名的 url 是问题所在,因为在 CMD 中使用curl 可以正常工作:

>curl -X PUT -H 'Content-Type:image/jpeg' -T "71k4prNp07S._UF1000,1000_QL80_.jpg" -L "pre-signed-url-here"

我真的希望有人能帮忙。

image amazon-s3 curl fetch-api
1个回答
0
投票

事实证明,AWS 服务器上未设置 CORS,这就是导致问题的原因。允许我的域名解决了问题

© www.soinside.com 2019 - 2024. All rights reserved.