Render "ReactJS" app using an Express server and configure proxy

Posted: 01-02-2023 | Views: 93
Render "ReactJS" app using an Express server and configure proxy

Create "server.js" file in root directory
const express = require("express");
const path = require("path");

const { justPipeProxy } = require("./proxyHelpers");
const app = express();
const port = process.env.PORT || 1234;

const buildFolderPath = path.join(__dirname, "/build");

app.use(express.static(buildFolderPath));

app.get("/proxy/*", justPipeProxy);
app.post("/proxy/*", justPipeProxy);
app.put("/proxy/*", justPipeProxy);
app.delete("/proxy/*", justPipeProxy);

app.get("*", (req, res) => {
  res.sendFile(path.join(buildFolderPath, "index.html"));
});

app.listen(port, () => console.log(`Listening on port ${port}`));
Create "proxyHelpers.js" file in root directory
const http = require("http");

exports.justPipeProxy = (client_req, client_res) => {
  let url = client_req.url.replace("/proxy", "");
  var options = {
    hostname: "88.88.88.88", // your ip
    port: "1234", // your port
    path: `${url}`,
    method: client_req.method,
    headers: {
      ...client_req.headers,
    },
  };
  var _proxy = http.request(options, function (res) {
    client_res.writeHead(res.statusCode, res.headers);
    res.pipe(client_res, {
      end: true,
    });
  });
  client_req.pipe(_proxy, {
    end: true,
  });
};
Examle usage (create api.service.js)
import axios from "axios";

const apiUrl = "/proxy";

export const getCountryList = async () =>
  (await axios.get(`${apiUrl}/api/country/getall`)).data;
A sample screenshot of the folder structure

Screenshot 2023-02-01 145459.png

Add comment