Search code examples
javascriptreactjsexpressherokufetch

Problem with getting data with Fetch - JavaScript


With the Postman program I download my shopping list from https://lit-brushlands-92375.herokuapp.com/api/items with GET

I would like to do the same in the browser console or on a website with code:

fetch('https://lit-brushlands-92375.herokuapp.com/api/items')
  .then(response => response.json())
  .then(data => console.log(data));

It returns the following error

VM89: 1 GET https://lit-brushlands-92375.herokuapp.com/api/items net :: ERR_FAILED

What am I doing wrong? What can be done better?


Solution

  • Front-end and Back-end are on Heroku. I received a CORS error. I added the following code to the main file of the back-end layer:

    app.use((req, res, next) => {
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader(
          'Access-Control-Allow-Headers',
          'Origin, X-Requested-With, Content-Type, Accept, Authorization'
        );
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE');
      
        next();
      });
    

    Thanks to this, I obtained a satisfactory effect in the form of downloaded data.