代码之家  ›  专栏  ›  技术社区  ›  Abhishek Rawal

AWS S3给出错误“调用链期间出现异常:无法分析请求(格式不正确(无效令牌):第1行,第0列),接收到无效XML:”

  •  0
  • Abhishek Rawal  · 技术社区  · 1 年前

    我使用node.js使用localstack将图像上传到本地环境中的s3 bucket

    这是我的API代码:

    const s3 = new AWS.S3({
      accessKeyId: 'testKEYId',
      secretAccessKey: 'testSecret',
      region: 'ap-south-1',
      sslEnabled: false,
      endpoint: 'http://localhost:4566',
    });
    
    app.post('/upload-1', upload.any(), (req, res) => {
      const imagePath = './myfolder/my-image.jpg'; // Update with your image file path
      const bucketName = 'my-buckert'; // Update with your S3 bucket name
      const remoteFileName = 'uploaded_image.jpg';
    
      const fileContent = fs.readFileSync(imagePath);
    
      console.log(fileContent);
    
      const params = {
        Bucket: bucketName,
        Key: remoteFileName,
        Body: fileContent,
      };
    
      const bucketParams = {
        Bucket: bucketName,
      }
    
      s3.upload(params, (err, data) => {
        if (err) {
          console.error('Error uploading image to S3:', err);
        } else {
          console.log('Image uploaded successfully. S3 location:', data.Location);
        }
      });
    });
    

    当我调用此API时,我会得到以下错误:

    调用链期间发生异常:无法分析请求(格式不正确 (无效标记):第1行,第0列),收到无效XML:

    参考屏幕截图: enter image description here

    0 回复  |  直到 1 年前
        1
  •  2
  •   bentsku    1 年前

    此问题源于使用 Virtual-Hosted 使用时针对LocalStack的样式请求 localhost 作为端点。

    您的SDK正在为主机准备bucket,这将导致如下请求:
    http://my-buckert.localhost:4566/uploaded_image.jpg
    如果存储桶名称后面没有跟 .s3. ,并将此请求视为 CreateBucket 呼叫

    这里的文档中概述了两种解决方案: https://docs.localstack.cloud/user-guide/aws/s3/#path-style-and-virtual-hosted-style-requests

    在您的情况下,最简单的方法是使用 s3ForcePathStyle 为您的客户。 以这种方式创建客户端应该可以解决您的问题:

    const s3 = new AWS.S3({
      accessKeyId: 'test',  // I would advise to use `test` and `test` for the keys
      secretAccessKey: 'test',
      region: 'ap-south-1',
      sslEnabled: false,
      endpoint: 'http://localhost:4566',
      s3ForcePathStyle: true,
    });
    

    有关javascript AWS SDK配置的更多信息,请点击此处: https://docs.localstack.cloud/user-guide/integrations/sdks/javascript/

        2
  •  1
  •   user2628783    1 年前

    我也面临同样的问题,@bentsku提到的原因是正确的。启用pathStyleAccess后,一切都对我有效:)。

    这是我的S3客户端创建代码

       private static AmazonS3 getLocalS3() {
        BasicSessionCredentials awsCreds = new BasicSessionCredentials("test", "test", "");
        return AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:4566", "us-east-2"))
                .enablePathStyleAccess()
                .build();
    }
    

    非常感谢@bentsku