can't send even test data from backend(express) to frontend(react component) both of m servers are running but still icant receive data from backend.
what i receive is a readablestream and after decoding this i got react main page html page in the console.
backend code block ( index.js)
import express from 'express'
import cors from 'cors'
const app=express()
const PORT=3000||5000
const options={
origin:"my-react-localhost-which-i can't paste here",
method:"GET,POST,PUT,DELETE",
credentials:true
}
app.use(cors(options))
app.use(express.json())
app.get("/",(req,res)=>{
res.json({message:"i am index"}).status(200) or res.send({message:"i am index"}).status(200)
})
app.listen(PORT,()=>{
console.log(`App is running on port:${PORT}`)
})
App.jsx code(react component)
const getData=async()=>{
const response= await fetch('api-running-locally')
console.log(response)
return response;
}
useEffect(()=>{
getData()},[])
both my backend and frontend running but still i can't get anything

Tuhin PaulRank #7 · 71.9K reputationPosted Jan 21, 2025, 1:48 PM EST
You must provide the full backend URL (
http://localhost:3000) if not using a proxy. Also check thefetchAPI 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 Check console for data ; }; export default App;Tuhin PaulRank #7 · 71.9K reputationPosted Jan 21, 2025, 1:52 PM EST
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.jsonwith aproxykey:{ "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 Check console for data ; }; export default App;package.jsonroutes/requests tohttp://localhost:3000, eliminating the need for CORS configuration in development.umair mohsinRank #3,092 · 463 reputationPosted Jan 21, 2025, 2:45 PM EST
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