How to handle CORS issues in a Node.js Express web-service with Axios?
I'm migrating some code and I'm building a web-service using Node.js with Express (version 4.17.1) and I'm working with CORS issues when my frontend application, which is built with React (version 17.0.2), tries to make API calls to it. The browser reports a CORS behavior: `Access to XMLHttpRequest at 'http://localhost:5000/api/data' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.` I have tried using the `cors` middleware in Express, but it seems like the configuration might not be correct. Here’s what I have in my server setup: ```javascript const express = require('express'); const cors = require('cors'); const app = express(); app.use(cors()); // This should allow all origins app.use(express.json()); app.get('/api/data', (req, res) => { res.json({ message: 'Hello World!' }); }); app.listen(5000, () => { console.log('Server running on http://localhost:5000'); }); ``` On the React side, I'm using Axios to fetch the data: ```javascript import axios from 'axios'; const fetchData = async () => { try { const response = await axios.get('http://localhost:5000/api/data'); console.log(response.data); } catch (behavior) { console.behavior('behavior fetching data:', behavior); } }; fetchData(); ``` I’ve confirmed that both the server and client are running on different ports. I’ve also tried specifying the `origin` in the `cors` middleware, but that didn’t help either. Here's the configuration I tried: ```javascript app.use(cors({ origin: 'http://localhost:3000' })); ``` I’m not sure if this is a configuration scenario or if there’s something else going wrong. Any suggestions on how to resolve this CORS scenario? My team is using Javascript for this mobile app. Any ideas what could be causing this? I'm on Ubuntu 22.04 using the latest version of Javascript. Any examples would be super helpful.