首页 > 解决方案 > 从 Nuxt 上传到 AWS S3 存储桶时出现 500 内部服务器错误

问题描述

我正在尝试使用Nuxt 应用程序的 Vue 组件中的aws-sdk v3将文件上传到 AWS S3。

这是我上传它的方式。

<script>
export default {
...
methods: {
onSubmit(event) {
    event.preventDefault()
    this.addPhoto()
},
addPhoto() {
  // Load the required clients and packages
  const { CognitoIdentityClient } = require('@aws-sdk/client-cognito-identity')
  const { fromCognitoIdentityPool } = require('@aws-sdk/credential-provider-cognito-identity')
  const {
    S3Client,
    PutObjectCommand,
    ListObjectsCommand,
    DeleteObjectCommand,
  } = require('@aws-sdk/client-s3')

  const REGION = 'us-east-1' // REGION
  const albumBucketName = 'samyojya-1'
  const IdentityPoolId = 'XXXXXXX'

  const s3 = new S3Client({
    region: REGION,
    credentials: {
      accessKeyId: this.$config.CLIENT_ID,
      secretAccessKey: this.$config.CLIENT_SECRET,
      sessionToken: localStorage.getItem('accessToken'),
    },
  })

  var file = this.formFields[0].fieldName
  var fileName = this.formFields[0].fieldName.name
  var photoKey = 'user-dp/' + fileName
  var s3Response = s3.send(
    new PutObjectCommand({
      Bucket: albumBucketName,
      Key: photoKey,
      Body: file,
    }),
  )
  s3Response
    .then((response) => {
      console.log('Successfully uploaded photo.' + JSON.stringify(response))
    })
    .catch((error) => {
      console.log(
        'There was an error uploading your photo: Error stacktrace' + JSON.stringify(error.message),
      )
      const { requestId, cfId, extendedRequestId } = error.$metadata
      console.log({ requestId, cfId, extendedRequestId })
    })
},

...

}
</script>

现在的问题是浏览器抱怨 CORS。

s3上传时出现CORS错误

这是我在 AWS S3 上的 CORS 配置

s3 CORS 配置

  1. 我在使用 SDK 创建上传请求时怀疑某些事情。(我愿意使用比我正在使用的更好的 API)。
  2. 允许 CORS 的 Nuxt 设置。
  3. S3 CORS 配置上的其他内容
  4. chrome 开发工具上的网络选项卡显示预取的内部服务器错误 (500)。(不知道为什么我们在这里看到 2 个条目) 感谢有关如何调试它的任何指针。没有 OPTIONS HTTP 动词的网络选项卡快照 1。 这首先被称为 带有 OPTIONS HTTP 动词的网络选项卡快照 2

标签: vue.jsamazon-s3nuxt.jsamazon-cognitohttp-status-code-500

解决方案


在存储桶策略中使用这个

 {
"Version": "2008-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Principal": {
            "AWS": "*"
        },
        "Action": [
            "s3:GetObjectAcl",
            "s3:GetObject",
            "s3:PutObject",
            "s3:PutObjectAcl",
            "s3:ListMultipartUploadParts"
        ],
        "Resource": "arn:aws:s3:::YOUR_BUCKET_NAME/*",
        "Condition": {
            "StringLike": {
                "aws:Referer": "https://example/*"
            }
        }
    }
]}

并使用您的存储桶区域

const s3 = new aws.S3({
    apiVersion: 'latest',
    accessKeyId: process.env.AWS_ACCESS_KEY_ID_CUSTOM,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY_CUSTOM,
    region: 'us-west-1',
})

在此处输入图像描述


推荐阅读