Home > Net >  How to connect and deploy React app with Node js backend?
How to connect and deploy React app with Node js backend?

Time:11-15

I have completed my first project in MERN stack but now I am struggling to deploy it on hiroku. Till now I was running both react and node code on different ports.

This are the files

enter image description here

client folder is frontend(React). App.js in Node is

const express = require("express");
const app = express();

const userRouter = require("./routes/userRoutes");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const compression = require("compression");

app.use(cors());

app.use(cookieParser());

app.use(express.urlencoded({ extended: true, limit: "10kb" }));
app.use(compression());

app.use("/api/v1/users", userRouter);
module.exports = app;

App.js in React is

import React from "react";
import "./App.css";
import Home from "./mainPages/home";
import Register from "./components/authentication/register";

import { Route, Switch } from "react-router-dom";

function App() {
  return (
    <div className="app">
      
      <Switch>
        <Route
          exact
          path="/"
          component={() => (<Home/>)} />
        <Route
          exact
          path="/register"
          component={() => (<Register/>)} />
        
      </Switch>
    </div>
  );
}

export default App;

Registeration data from client side is send like this

axios({ method: "POST", url: "http://localhost:3000/api/v1/user/register", data: data, headers: header });

How to connect client and server to deploy on hiroku?

CodePudding user response:

It is ideal to keep client folder outside server folder.

Step 1: Build your React App and take out the contents in the output folder (dist folder)

Step 2: Deploy your front end in any static hosting services eg(AWS S3 or in any hosting providers)

Step 3: Deploy your back end API in Heroku or any node hosting provider

Step 4: Update the AJAX end points in front end.

Step 5: Thoroughly test and release

  • Related