0

I have the build files (from npm run build) of the react application in the /public folder on my backend folder.

This is what is in my index.js on my backend

const express = require('express')
const mysql = require('mysql');

const path = require('path')

const app = express()
app.use(express.static(path.join(__dirname + "/public")))
app.use(express.json())

const PORT = 5000
app.listen(PORT)


app.get('/*', function(req, res) {
    res.sendFile(path.join(__dirname, '/public/index.html'), function(err) {
        if (err) {
            res.status(500).send(err)
        }
    })
})

const db = mysql.createConnection({
    user: "root",
    host: "localhost",
    password: "",
    database: "project_db",
});

const users =
[
    { id: 1,name: "Andrew" },
    { id: 2, name: "Steve" },
    { id: 3, name: "John" },
    { id: 4, name: "Michael" },
    { id: 5, name: "Christian"  }
];

app.get("/api/users", (req, res) => {
    res.json(users);
})

app.post("/api/register", (req, res) => {
    const username = req.body.username;
    const password = req.body.password;
    const email = req.body.email;
    
    db.query("INSERT INTO users (name, password, email) VALUES (?, ?, ?)", [username, password, email]);

    res.send({
        "message": "account registered",
        "status": 1,
    });
});

App.js on my react app

import { Route, Routes } from 'react-router-dom'
import './components/App.css'
import Home from './pages/Home'
import Login from './pages/Login'
import Register from './pages/Register'

function App() {
    return (
        <>
            <Routes>
                <Route path="/" element={<Home />} />
                <Route path="/login" element={<Login />} />
                <Route path="/register" element={<Register />} />
                <Route path="*" element={ <h1>Not found (404)</h1> } />
            </Routes>
        </>
    );
}

export default App;

My question: When I go to http://localhost:5000/api/users it gets the 404 not found from my react app

How can I fix this problem?

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Freezy
  • 136
  • 15
  • Does this help? https://stackoverflow.com/questions/19313016/catch-all-route-except-for-login – Yatin Gupta Jan 04 '23 at 17:54
  • What ports are the React app and backend running on, and why are you trying to navigate to one of your endpoints? – Drew Reese Jan 04 '23 at 18:02
  • The react app runs on port :3000 and the backend on :5000. But I search on the internet and found that if I will want to deploy the project (frontend+backend) on a webhost I need to have a folder inside the backend that contains the build files from react app that can run the frontend+backend on the same port without having to set up a subdomain separatly like api.domain.ro to acces my data and send to main domain www.domain.ro. (I don't know if it is a good decision) @DrewReese – Freezy Jan 04 '23 at 18:06

1 Answers1

1

List your backend API endpoints before the "*" "endpoint" that returns the React app.

const express = require('express');

...

// Backend APIs
app.get("/api/users", (req, res) => {
  res.json(users);
})

app.post("/api/register", (req, res) => {
  const username = req.body.username;
  const password = req.body.password;
  const email = req.body.email;
    
  db.query("INSERT INTO users (name, password, email) VALUES (?, ?, ?)", [username, password, email]);

  res.send({
    "message": "account registered",
    "status": 1,
  });
});

// Frontend React app routes
app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname, '/public/index.html'), function(err) {
    if (err) {
      res.status(500).send(err)
    }
  })
});
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Thank you! Now its working. One more thing, what would you recommand if I want to deploy my application on a web hosting server. Should I have a folder that contains the backend files and also a folder that contains the files from my ``reactapp/build/`` folder (something like i have right know) or to have a separate subdomain (without the build files from my reactapp) like ``api.mydomain.com`` for all API calls that will comes from the main domain like ``www.mydomain.com`` ? – Freezy Jan 04 '23 at 18:25
  • @Freezy That's entirely subjective and may possibly depend on the hosting service. I'm afraid I don't have a solid answer for you on that one. – Drew Reese Jan 04 '23 at 18:36