skid skid - 4 years ago 181
HTTP Question

Access Amazon s3 using http in angular2

I have a .json file in my Amazon s3 bucket when i try to access the file using http call in my Angular2 app i am getting an error


Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at
https://s3.us-east-2.amazonaws.com/....../list.json.
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).


I made the file in my bucket to be public and gave the access as read, write and edit.

Here is my Angular Code:

getValue(){
return this._http.get('https://s3.us-east-2.amazonaws.com/........./list.json').toPromise().then(res => <Contact[]> res.json().data)
.then(data => {return data;});
}


My cross origin XML in AWS

<CORSConfiguration>
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>


Can anyone help me resolving this issue
Thanks in advance

Answer Source

Probably nothing to do with your Angular code. Take a look at AWS S3 docs on CORS. You need to set up a CORS configuration in your bucket. The docs provide this as an example:

<CORSConfiguration>
 <CORSRule>
   <AllowedOrigin>http://www.example1.com</AllowedOrigin>

   <AllowedMethod>PUT</AllowedMethod>
   <AllowedMethod>POST</AllowedMethod>
   <AllowedMethod>DELETE</AllowedMethod>

   <AllowedHeader>*</AllowedHeader>
 </CORSRule>
 <CORSRule>
   <AllowedOrigin>http://www.example2.com</AllowedOrigin>

   <AllowedMethod>PUT</AllowedMethod>
   <AllowedMethod>POST</AllowedMethod>
   <AllowedMethod>DELETE</AllowedMethod>

   <AllowedHeader>*</AllowedHeader>
 </CORSRule>
 <CORSRule>
   <AllowedOrigin>*</AllowedOrigin>
   <AllowedMethod>GET</AllowedMethod>
 </CORSRule>
</CORSConfiguration>

The docs also say:

To configure your bucket to allow cross-origin requests, you create a CORS configuration, an XML document with rules that identify the origins that you will allow to access your bucket, the operations (HTTP methods) will support for each origin, and other operation-specific information.

This allows you to decide which origins can access your bucket (for example, if you want all origins to be able to access it, you can use the wildcard *).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download