使用带有React的S3 API在AWS中获取ListBuckets方法?

时间:2018-09-12 11:10:38

标签: reactjs amazon-web-services amazon-s3

我正在使用S3 Api检索ListBuckets方法。这是我的反应代码

import React, { Component } from "react";
export default class Listbuckets extends Component {

 handleClick = () => {
    var AWS = require('aws-sdk')
    // Set the region 
    AWS.config.update({
        region: "ap-south-1"
       });

    // Create S3 service object
 var s3 = new AWS.S3({apiVersion: '2006-03-01'});

    var params = {};
     s3.listBuckets(params, function(err, data) {
       if (err) console.log(err, err.stack); // an error occurred
       else   
       {  
        console.log(data);
      }       // successful response

     });
}
render() {
    return (
      <div className="container">
          <h1>This is the stats.</h1>
        <button onClick={this.handleClick}>Click Me</button>
        </div>
    )
  }
 }

这是我为所有存储桶启用的CORS配置。

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

但是当我在响应中运行此命令时,会出现这样的错误

xhr.js:83 OPTIONS https://s3.ap-south-1.amazonaws.com/ 403 (Forbidden)
Failed to load https://s3.ap-south-1.amazonaws.com/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
Error: Network Failure
    at XMLHttpRequest.<anonymous> (xhr.js:52) "NetworkingError: Network Failure
    at XMLHttpRequest.<anonymous> (http://localhost:3000/static/js/bundle.js:76976:34)"

当我在node.js中运行相同的代码时,它向我显示了正确的响应。我不知道我的反应代码中缺少什么。这是我的node.js代码

var AWS = require('aws-sdk');
// Set the region 
AWS.config.update({
    region: "ap-south-1"
   });

// Create S3 service object
s3 = new AWS.S3({apiVersion: '2006-03-01'});

var params = {};
 s3.listBuckets(params, function(err, data) {
   if (err) console.log(err, err.stack); // an error occurred
   else   
   {    
       console.log(data)
    //    console.log(data.Buckets.map(x => x.Name))
  }       // successful respons

 });

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

s3的ListBuckets方法不支持cors。这是公开问题in github