CodexBloom - Programming Q&A Platform

Handling CORS implementing Express.js and Axios in a React application

👀 Views: 158 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-07
javascript reactjs express axios cors JavaScript

I've been researching this but I'm collaborating on a project where I'm developing a React application using Axios to interact with a REST API hosted on an Express.js server. However, I'm running into CORS issues when making requests from the frontend to the backend. Specifically, I'm getting a `Access-Control-Allow-Origin` behavior in the console when I try to fetch data. Here's the code snippet from my Express server: ```javascript const express = require('express'); const cors = require('cors'); const app = express(); app.use(cors()); // I expected this to handle CORS issues app.get('/api/data', (req, res) => { res.json({ message: 'Hello, World!' }); }); app.listen(5000, () => { console.log('Server is running on http://localhost:5000'); }); ``` And here is how I'm making the request from my React app: ```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); } }; useEffect(() => { fetchData(); }, []); ``` I've checked that the server is running, and I'm able to access the API directly through my browser. I initially thought that adding `cors()` middleware to my Express setup would resolve the scenario. I've also tried specifying allowed origins in the CORS options like this: ```javascript app.use(cors({ origin: 'http://localhost:3000' })); ``` However, I still get the same behavior. I've verified that there are no network issues, and both the React app and Express server are running on localhost but on different ports (3000 and 5000, respectively). Is there something I'm missing or misconfiguring regarding CORS in this setup? Any suggestions on how to troubleshoot this further would be greatly appreciated! I'm on Ubuntu 22.04 using the latest version of Javascript. I appreciate any insights! Any advice would be much appreciated.