2
If you want a simpler and shorter approach without manually configuring CORS or handling cross-origin issues, you can use a proxy in your React app's package.json
. This way, you can use relative URLs in your fetch requests, and the React development server will automatically forward requests to your backend.
In your React project, update package.json
with a proxy
key:
{
"name": "react-app",
"version": "0.1.0",
"private": true,
"dependencies": {
// Your dependencies
},
"proxy": "http://localhost:3000" // Backend URL
}
No CORS setup is required since the proxy handles it. Just keep your backend minimal:
import express from 'express';
const app = express();
const PORT = 3000;
app.use(express.json());
// Example API route
app.get('/', (req, res) => {
res.json({ message: 'I am index' });
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Since the proxy is set, you can use relative URLs (/
) in your fetch requests:
import React, { useEffect } from 'react';
const App = () => {
const getData = async () => {
try {
const response = await fetch('/'); // Proxy forwards to http://localhost:3000/
const data = await response.json();
console.log(data); // Should log: { message: 'I am index' }
} catch (error) {
console.error('Error fetching data:', error);
}
};
useEffect(() => {
getData();
}, []);
return <div>Check console for data</div>;
};
export default App;
- The proxy in
package.json
routes /
requests to http://localhost:3000
, eliminating the need for CORS configuration in development.
- The setup is minimal, and you don't need to hardcode backend URLs in your frontend.
- This approach is ideal for development. In production, you must configure your backend to handle CORS or deploy both frontend and backend on the same domain.

2
You must provide the full backend URL (http://localhost:3000
) if not using a proxy. Also check the fetch
API decodes the response as JSON (response.json()
).
import express from 'express';
import cors from 'cors';
const app = express();
const PORT = 3000; // Use a specific port, avoid `||` for PORT assignment in your example.
const options = {
origin: 'http://localhost:3001', // Replace with your React app's URL and port.
methods: ['GET', 'POST', 'PUT', 'DELETE'], // Use array for CORS methods.
credentials: true,
};
app.use(cors(options));
app.use(express.json());
// Example GET route
app.get('/', (req, res) => {
res.status(200).json({ message: 'I am index' }); // Set status before sending response.
});
app.listen(PORT, () => {
console.log(`App is running on port: ${PORT}`);
});
React JS code:
import React, { useEffect } from 'react';
const App = () => {
const getData = async () => {
try {
const response = await fetch('http://localhost:3000/', {
method: 'GET', // Specify method if needed.
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error(`Error: ${response.status}`);
}
const data = await response.json();
console.log(data); // Should log: { message: 'I am index' }
} catch (error) {
console.error('Failed to fetch data:', error);
}
};
useEffect(() => {
getData();
}, []);
return <div>Check console for data</div>;
};
export default App;

0
since i have created react project from vite so i added proxy to vite.config.js file and it is these line
server:{
Proxy:{
"/api/":"http://localhost:3000"
}
},
my fetch api code
const response = await fetch('about', {
method: 'GET', // Specify method if needed.
headers: {
'Content-Type': 'application/json',
},
});
that code still not giving desired output