尝试使用 Storage.put() 时出现无凭据错误

Getting a No Credentials error when trying to use Storage.put()

当我尝试将文件放入我的存储时收到 No credentials error。我遵循了这个指南:https://medium.com/@anjanava.biswas/uploading-files-to-aws-s3-from-react-app-using-aws-amplify-b286dbad2dd7.

import Storage from '@aws-amplify/storage';

export const uploadFile = async () => {
    SetS3Config('site-nocas-bucket-amplify', 'protected');

    try {
        await Storage.put('text.txt', 'Hello');
    } catch (err) {
        console.error(err);
    }
};

我正在使用此代码进行测试。

这是我对放大和存储的手动配置:

import Storage from '@aws-amplify/storage';

export function configureAmplify() {
    Amplify.configure({
        Auth: {
            identityPoolId: process.env.REACT_APP_identityPoolId,
            region: process.env.REACT_APP_region,
            userPoolId: process.env.REACT_APP_userPoolId,
            userPoolWebClientId: process.env.REACT_APP_userPoolWebClientId
        },
        Storage: {
            bucket: process.env.REACT_APP_bucket_name,
            region: process.env.REACT_APP_region,
            identityPoolId: process.env.REACT_APP_identityPoolId
        }
    });
}

export function SetS3Config(bucket, level) {
    Storage.configure({
        bucket: bucket,
        level: level,
        region: 'eu-west-1',
        identityPoolId: process.env.REACT_APP_identityPoolId
    });
}

所以, 我把解决这个问题的步骤放在这里,

第 1 步:

如果您尝试上传文件而没有 登录网络应用程序,那么您的 Amplify 和 Storage 手动配置应该如下所示:

import Storage from '@aws-amplify/storage';

export function configureAmplify() {
    Amplify.configure({
        Auth: {
            identityPoolId: process.env.REACT_APP_identityPoolId,
            region: process.env.REACT_APP_region,
            userPoolId: process.env.REACT_APP_userPoolId,
            mandatorySignIn: false,
            userPoolWebClientId: process.env.REACT_APP_userPoolWebClientId
        },
        Storage: {
            bucket: process.env.REACT_APP_bucket_name,
            region: process.env.REACT_APP_region,
            identityPoolId: process.env.REACT_APP_identityPoolId
        }
    });
}

这一行:

mandatorySignIn: false

这可以防止强制用户对您的应用程序进行身份验证,您的 Cognito 身份将通过该身份验证识别您并为您提供对 AWS 资源的访问权限。

如果仍然出现错误,试试这个:

第 2 步:

  1. npm 更新
  2. 删除节点模块文件夹中的@aws-amplify 文件夹
  3. npm 安装。

我希望这会奏效。