Home > Net >  React routes gets conflicted with express routes
React routes gets conflicted with express routes

Time:01-05

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?

CodePudding user response:

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)
    }
  })
});
  • Related