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
umair mohsinPosted Jan 21, 2025, 7:45 PM
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
Tuhin PaulPosted Jan 21, 2025, 6:52 PM
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:No CORS setup is required since the proxy handles it. Just keep your backend minimal:
Since the proxy is set, you can use relative URLs (
/) in your fetch requests:package.jsonroutes/requests tohttp://localhost:3000, eliminating the need for CORS configuration in development.Tuhin PaulPosted Jan 21, 2025, 6:48 PM
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()).React JS code: