0

I am using reactjs and axios

I have this error when fetching the png from S3 to the local environment.

Access to fetch at 'https://xxx-xxx-xxx.s3.ap-northeast-1.amazonaws.com/0.png' from origin 'http://localhost:8021' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I try to send header

 let headers = new Headers();
 headers.append('Access-Control-Allow-Origin','*');
 headers.append('Access-Control-Allow-Credentials', 'true');
 fetch(fileUrl,{headers: headers}).then(function(response){
 })

and S3 has this CORS setting.

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET",
            "POST",
            "PUT"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [
            "ETag"
        ],
        "MaxAgeSeconds": 3000
    }
]

Somehow my header is not sent correctly or am I wrong anywhere else?


Another trial

I install npm install http-proxy-middleware

and make src/setupProxy.js

const { createProxyMiddleware } = require("http-proxy-middleware");
console.log("setup is called");
module.exports = function (app) {
  app.use(
    "/",
    createProxyMiddleware({
      target: "https://xxx-xxx-xxx.s3.ap-northeast-1.amazonaws.com/0.png",
      changeOrigin: true,
    })
  );
};

then server start with webpack --mode development --watch

However nothing changes, even console.log("setup is called"); is not called

How can I solve this?

whitebear
  • 11,200
  • 24
  • 114
  • 237
  • I just wonder that the OPTIONS method acceptable? you can check it at the network tap in the dev mode. – Humanoid Mk.12 Jul 07 '23 at 02:03
  • `fetch(fileUrl,{headers: headers}).then(function(response)` is a REQUEST ... `Access-Control-Allow-Origin` are RESPONSE headers - stop putting RESPONSE headers in a REQUEST - that will only make your problem harder to solve – Jaromanda X Jul 07 '23 at 02:12

1 Answers1

1

You need to set the mode to cors and the Content-Type to image/png to indicate that you are fetching an image from a different origin. You also need to set the Authorization header if your S3 bucket requires authentication.

For example:

let headers = new Headers();
headers.append("Content-Type", "image/png");
headers.append("Authorization", `Bearer ${token}`);
fetch(fileUrl, { mode: "cors", headers: headers })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

You can configure your S3 bucket to allow CORS requests from your origin. You need to edit the CORS configuration of your bucket and add a rule that specifies the allowed origins, methods, headers, and exposed headers for your requests. You can use the AWS console or the AWS CLI to do this.

For example:

<CORSConfiguration>
  <CORSRule>
    <AllowedOrigin>http://localhost:8000</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
    <ExposeHeader>ETag</ExposeHeader>
  </CORSRule>
</CORSConfiguration>

To learn more, see:

And for another trial, I think you can try to delete the package-lock.json file and the node_modules directory, and then run npm install again.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Pluto
  • 4,177
  • 1
  • 3
  • 25
  • Thank you, I wrote the script from the scratch like your answer, it works. However if I put this in the middle of my script, it shows the same error, maybe I use axios for another url before that, It might be relevant .... ? however your help makes me step forward. thankyou – whitebear Jul 07 '23 at 03:31
  • You're welcome. I'm glad to hear that it works. If you are using `axios` for another url before that, you might need to check if the proxy is interfering with your other requests. You can try to use a more specific path for your proxy, such as "/api/*" instead of "/". This way, only the requests that start with "/api/" will be proxied to the target url, and the rest will be handled normally. – Pluto Jul 07 '23 at 03:49