3
Answers

how to send data from backend to front end or vice versa

Photo of umair mohsin

umair mohsin

Jan 21
415
1

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

Answers (3)

2
Photo of Tuhin Paul
39 34.7k 314.7k Jan 21

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
Photo of Tuhin Paul
39 34.7k 314.7k Jan 21

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
Photo of umair mohsin
1.3k 405 74.8k Jan 21

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