Search code examples
reactjscorsfetchuse-effectaccess-control

How to fix CORS error "http://localhost:3000 is not allowed by Access-Control-Allow-Origin" in a react-app?


I did find a solution approach to this for express servers, but I am not able to implement the same to my react-app.

referred to this. Please suggest. (I am beginner to CORS)

Here is my App.js file:

import { useEffect, useState } from "react";
import "./App.css";

function App() {

  const APP_ID = "--"
  const APP_KEY = "--"

  const [counter, setCounter] = useState(0);

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

  const getRecipes = async () => {
    const response = await fetch(`https://api.edamam.com/search?q=chicken&app_id=${APP_ID}&app_key=${APP_KEY}&from=0&to=3&calories=591-722&health=alcohol-free`);
    const data = response.json();
    console.log(data);
  }

  return <div className="App">
    <form className="search-form">
      <input className="search-bar" type="text" placeholder="Search query here!" />
      <button
        className="search-button" type="submit">
        Search
      </button>
    </form>
    <h1 onClick={() => setCounter(counter + 1)}>{counter}</h1>
  </div>;
}

export default App;

Solution

  • For production and almost all use cases, this needs to be done on a server (i.e the backend you are using, usually running node.js, not the frontend on react).

    However, create-react-app does let you set a proxy on the client-side to test during development, albeit it is not recommended, since if you forget to remove it when pushing your code out to production, its can be a serious security issue. If its just a learning project you can do this:

    If this is your API: http://123.4.345.53:7000/api/profile/ add this part in your package.json file: "proxy": "http://123.4.345.53:7000/" Then you can do the following:

    React.useEffect(() => {
    axios
        .get('api/profile/')
        .then(function (response) {
            console.log(response);
        })
        .catch(function (error) {
            console.log(error);
        }); 
    });
    

    If you decide to use a dedicated backend, and it runs node.js, this is done like so:

    var app = express();
    
    app.use(function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      next();
    });