0

I am using React Filepond and the uploading part is working fine. But when I go to an existing record and try to display the image, I get a CORS error:

Access to XMLHttpRequest at 'http://localhost:8000/img/myImg.jpg' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

in app.js on my node server I have the below but I still get the cors error using the cors package

const cors = require("cors");
app.use(cors());
app.options("*", cors());

In React I have the following:

  state = {
    data: {
      title: "",
      bgImg: ""
    },
    errors: {},
    files: [
      {
        source: "myImg.jpg",

        options: {
          type: "local"
        }
      }
    ]
  };

    <FilePond
      ref={ref => (this.pond = ref)}
      files={this.state.files}
      allowMultiple={false}
      maxFiles={1}
      name="bgImg"
      server={{
        process: "http://localhost:8000/api/uploads/",
        load: "http://localhost:8000/img/"
      }}
      oninit={() => this.handleInit()}
      onupdatefiles={fileItems => {
        this.setState({
          files: fileItems.map(fileItem => fileItem.file)
        });
      }}
    />

In package.json I have also added a proxy:

"proxy": "http://localhost:8000/img",

Network tab -> headers tab shows

Request URL: http://localhost:8000/img/myImg.jpg
Referrer Policy: no-referrer-when-downgrade

Provisional headers are shown
Referer: http://localhost:3000/home-banner
user8463989
  • 2,275
  • 4
  • 20
  • 48
  • Test if the response in the developer tools network tab actually shows the required CORS headers. – Rik Aug 06 '19 at 06:09
  • @Rik, not sure if I am looking in the right place but I have updated my original question with what shows up. – user8463989 Aug 06 '19 at 06:32
  • https://ibb.co/LnZ6pf9 the access-control headers are what you need. – Rik Aug 06 '19 at 07:00
  • Is the CORS package on the node.js server not catering for that or do I need to also install that on the React project? – user8463989 Aug 06 '19 at 07:25
  • I don't know, I don't have a lot of experience with NodeJS, I do know this is something that is configured on the server not the client. – Rik Aug 06 '19 at 09:04
  • I will deploy this to see if I have the same issue on a live server as it's running on localhost at the moment and let you know... – user8463989 Aug 06 '19 at 09:06
  • @Rik, I am not sure if this is a suitable solution but I had to use cors anywhere to get it to work, it's the only thing that actually works for me. https://cors-anywhere.herokuapp.com – user8463989 Aug 06 '19 at 13:51

1 Answers1

0

Try installing cors plugin in your browser and access the api. Hope this helps..

const cors = require('cors')

const corsOptions = {
  origin: 'http://localhost:8000'
}

app.get('/img', cors(corsOptions), (req, res, next) => {
  //...
}) 
Venkatachalam
  • 16,288
  • 9
  • 49
  • 77
Ram Sankhavaram
  • 1,218
  • 6
  • 11