Search code examples
reactjsexpressmern

Why can't I call localhost localhost:5000 from localhost:3000 using fetch in react?


My react application running on localhost:3000 and in that I am making a GET request in my code using fetch to localhost:5000/users.

const [users, setUsers] = useState([]);

useEffect(() => {
  fetch('http://localhost:5000/users')
    .then(res => res.json())
    .then(data => setUsers(data))
}, []);

But I'm getting an error called

Access to fetch at 'http://localhost:5000/users' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.


Solution

  • It is a much discussed problem. Follow the steps below:

    If you are using nodejs or express js for your backend. Install the cors package in your express app.

    npm install cors
    

    And, include the following in your index.js file.

    var cors = require('cors')
    
    app.use(cors())
    

    That's it. It should work now. Don't forget to restart your node server.

    To understand it better, read this article.