【问题标题】:I am getting 400 bad request error while trying to upload image to aws s3 bucket using preSignedUrl. What is going wrong?尝试使用 preSignedUrl 将图像上传到 aws s3 存储桶时出现 400 错误请求错误。出了什么问题?
【发布时间】:2021-02-24 02:23:17
【问题描述】:

我正在为我的存储桶和后端的 nodejs 使用 IAM 配置。我整晚都在寻找解决方案。但找不到答案。

这是我在 aws 上的用户策略配置:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "s3:GetAccessPoint",
                "s3:PutAccountPublicAccessBlock",
                "s3:GetAccountPublicAccessBlock",
                "s3:ListAllMyBuckets",
                "s3:ListAccessPoints",
                "s3:ListJobs",
                "s3:CreateJob"
            ],
            "Resource": "*"
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::my-first-bucket-stephengr/*",
                "arn:aws:s3:::my-first-bucket-stephengr",
                "arn:aws:s3:*:041892289571:accesspoint/*",
                "arn:aws:s3:*:041892289571:job/*"
            ]
        }
    ]
}

后端代码: app.get("/api/upload", loginRequired, function(req, res){

  var key = `${req.user.id}/${uuid()}.png`;
  var fileName = key.split("/")[1];

  s3.getSignedUrl("putObject", {
      Bucket: "my-first-bucket-stephengr",
      ContentType: "image/png",
      Key: key

  }, (err, url) => {
      res.json({key, url, fileName});
  })

})

前端代码: 异步函数句柄提交(e){ e.preventDefault();

    var res = await axios.get("/api/upload", {headers: authHeader()});

    try{
    
        await axios.put(res.data.url, file, {headers: {ContentType: file.type}})

    }catch(err){
        console.log(err)
    }

    console.log(res.data);
}

【问题讨论】:

  • 上传如何?有什么细节吗?
  • 我的问题中包含了代码?有人帮忙吗?

标签: node.js amazon-web-services amazon-s3 aws-sdk-nodejs


【解决方案1】:

错误是由于地区造成的。在后端添加区域属性解决了这个问题:

    var s3 = new AWS.S3({
    accessKeyId: process.env.ACCESS_KEY_ID,
    secretAccessKey: process.env.SECRET_ACCESS_KEY,
    region: "ap-south-1"
    })

【讨论】:

    猜你喜欢
    • 2018-01-07
    • 2021-05-13
    • 2021-03-23
    • 2019-03-15
    • 2021-09-10
    • 2017-08-08
    • 2016-03-18
    • 2018-06-19
    • 2021-09-09
    相关资源
    最近更新 更多