1

I am unable to create bucket in AWS S3 server using aws-sdk. But I can add new folder and file in existing bucket but not able to create new. Below code, which I used to create a new bucket.

import AWS from "aws-sdk";

AWS.config.update({
region: config.region,
 accessKeyId: config.accessKeyId,
 secretAccessKey: config.secretAccessKey,
});
const s3 = AWS.S3();

s3.createBucket({ Bucket: "admin"}, (error, data) => {
  if(error.statusCode === 409){
  upload();
  }
  if (error) {
    console.log(error)
  } else {
    console.log(data);
  }
});
Tula Vinay
  • 11
  • 2
  • Are you creating a bucket with a name "admin"? If so, change that to a unique name. – shimo Nov 14 '21 at 21:41
  • I have tried with different words but still I get same error. – Tula Vinay Nov 14 '21 at 21:51
  • What is the error message saying? – shimo Nov 14 '21 at 22:02
  • This is the exact error I'm getting " Access to XMLHttpRequest at 'https://intel.s3.ap-south-1.amazonaws.com/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource." – Tula Vinay Nov 14 '21 at 22:06
  • That says CORS error. Just solve. This may help. https://stackoverflow.com/questions/57009371/access-to-xmlhttprequest-at-from-origin-localhost3000-has-been-blocked – shimo Nov 14 '21 at 22:12
  • Can you please be more specific because I'm new to react and the above link says to add cors options in server but I'm just making a request to S3 server using aws-sdk library I followed this [link](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-creating-buckets.html) – Tula Vinay Nov 14 '21 at 22:32
  • Perhaps on local machine it works without, right? But on localhost (react) you need to care CORS. – shimo Nov 15 '21 at 00:53

1 Answers1

0

I had the same problem, and I learnt that this is not possible today, because browsers enforce CORS restrictions, and AWS SDK has this limitation of treating buckets as resources, hence CORS apply even before they exist.

See https://github.com/aws/aws-sdk-js/issues/1112 for more details.

To fix this, you can call createBucket from any non-browser environment (server side), e.g. a lambda function, or a node server or cloud function.

Sanjay Verma
  • 1,390
  • 22
  • 40