0

I received the dreaded CORS error when hooking up my API. I am using the BeerDB one. I tried the plugin, adding the header, going into index.js but it does not seem to solve it. Still looking into it, my code for my App.js is below. It is a React app.

The next thing I can even think of is to refactor my API fetch call to use axios and use different syntax than currently being used.

import React, {useEffect, useState, Component} from 'react';
import './App.css';
import Beer from './Beer.js';

const App = () => {

  const App_Key = "b1322de05886eaf6bdd71b64c52d12b7"

  const [beers, setBeers] = useState([]);

  useEffect (() => {
    getBeers();
   }, []);

  const getBeers = async () => {
    const response = await fetch("http://api.brewerydb.com/v2/?key=b1322de05886eaf6bdd71b64c52d12b7");
    const data = await response.json();
    console.log(data); 
  }

  return(
    <div className="App">  
      <form>
        <input type="text" ></input>
        <button type="submit">Search</button>
      </form>

    { beers.map(beers => (<Beer /> )) }

    </div>
  );
}

export default App;
emporerblk
  • 1,063
  • 5
  • 20
voteforpedro
  • 45
  • 1
  • 1
  • 3
  • It's simple cors problem, you need from server to add Access-Control-Allow-Origin header, or write your own proxy on backend to pass data through it. – dark_gf May 19 '20 at 19:47
  • They don't provide allow headers. You need to proxy it in your own backend. There is no way around this unless they provide some other API that **DOES** add those headers. This is not something that your front-end can circumvent. – zero298 May 19 '20 at 19:48
  • 1
    You should also avoid putting API keys that you are [supposed to keep secret](https://www.brewerydb.com/developers/docs) in your question. You should request a new key now that it has been made public and delete the old one. – zero298 May 19 '20 at 20:10

1 Answers1

7

The CORS error is due to the destination server not allowing the browser to make a request. The browser is usually allowed to make a request to the same server from which the web page and the script included by it were downloaded.

Most often, the CORS error is a genuine error thrown by browser. It is aimed at preventing accidental or deliberate attempts to export data from one web page to an adversary's server.

But in the other times, CORS error is a blocker for genuine requirement of querying a trusted 3rd party server's API from a web page.

There are 2 ways to resolve the CORS problem:

Option # 1 (Recommended)

Update the target server's API to explicitly allow AJAX requests from the origin.

Example:

Suppose that the UI is served by http://localhost:3000 and the API is hosted on http://localhost:8080/rst/api

In this environment, any fetch request made from the UI components to http://localhost:8080/rest/api will be blocked due to CORS issues.

This is the case of genuine requirement to allow the origin of http://localhost:3000 to make requests to http://localhost:8080.

In order to allow fetch from http://localhost:3000 to http://localhost:8080,

The server running on http://localhost:8080 must be configured with the header option of

{'Access-Control-Allow-Origin': 'http://localhost:3000'}

This will then allow the UI components served by http://localhost:3000 to make fetch calls to http://localhost:8080


Option #2 Make a fetch call with no-cors mode

Note: This method is not recommended for production use. This may be used for testing purpose only

The fetch call can be made like a request from POSTMAN tool or url command by disabling the default cors checking. However, this method is not recommended for production environment. This must be used for testing only.

Here is an example of fetch call with cors check disabled:

  fetch(url, {
    method: 'POST', 
    mode: 'no-cors',
    headers: {
      'Content-Type': 'application/json'
    },
    body: {"key" : "some text"}
  })

More information:

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Gopinath
  • 4,066
  • 1
  • 14
  • 16
  • Thanks and that is the exact doc I was looking at, excuse me but I was a little confused given the doc showed calling the api a little differently so I am not sure where to put the header. I know it would be in fetch but – voteforpedro May 19 '20 at 20:45