How do i host react + node server on a local network

257 Views Asked by At

I want to host a react server plus a node server on a local network, the website has multiple pages and uses axios to send and receive data from the node server and in the package.json there is a proxy to guide react to the node server

  "proxy": "http://localhost:8080",
  "homepage": "./"

ps: i use express.js if that matters

2

There are 2 best solutions below

0
Apostolis16 On BEST ANSWER

I just used serve and npm run build and i can access it on lan

0
Aditya On

Ensure it's running on a specific port, for example port 8080

const express = require('express');
const app = express();
const port = 8080;

// Define your routes and middleware here

app.listen(port, () => {
  console.log(`Node server is running on port ${port}`);
});

now your React app is already configured with the "proxy" field in the package.json file its good

Run your React development server with:

npm start

By default, it should be running on port 3000.

now access react on local

access your React app from other devices on the same local network by finding your local IP address and specifying the port (usually 3000):

Find your local IP address from another device on the same network, open a web browser and enter http://your-local-ip:3000. now it would be accessible on local server not turn for making api requests

In your React app, use axios or any other HTTP client to make API requests to your Node server using the relative paths defined in your proxy.

For example, if you have a route in your Node server like this

app.get('/api/data', (req, res) => {
  // Handle the API request here
});

You can make a request from your React app like this

axios.get('/api/data')
  .then(response => {
    // Handle the response data
  })
  .catch(error => {
    // Handle errors
  });

The proxy configuration in package.json will automatically route the request to http://localhost:8080/api/data

Nowyour react app and Node server should work together on your local network.