skip to Main Content

<y application does not display when I launch npm run dev. Absolutely nothing is displayed on port 5173 (http://www.localhost:5173)

It displays "error 404" while my jsx should be displayed

None of my routes are displayed. Whether it is path=/ or others

I have tried several solutions without success

My back-end server works nevertheless. When I type "node app.js" on my terminal, there is indeed "Welcome to the home page!" which is displayed on port 3000

On the other hand, I do not know how to link my front-end and my back-end. But that is yet another problem. My main problem is that it gives me "error 404" when I type "npm run dev" in the terminal and launch the port on the web browser

I first thought it was because I didn’t allow port 5173 in my firewall. I tried, it still didn’t work

Then I thought it needed an openssl certificate with a valid key. So I downloaded openssl, implemented it in my code and modified the environment variables with the path. Without success

Here is the structure of my files in my React.js application:

front-end

back-end

Here is my package.json with the installed libraries:

start

rest

Here is my main.jsx:

// src/main.jsx
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { BrowserRouter as Router } from "react-router-dom";
import { ThemeProvider } from "@mui/material/styles";
import theme from "./theme"; // Assure-toi que ce chemin est correct
import "./App.css";

// Création du root pour React 18+
const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
  <React.StrictMode>
    <ThemeProvider theme={theme}>
      <Router>
        <App />
      </Router>
    </ThemeProvider>
  </React.StrictMode>
);

Here is my app.jsx with all my routes:

import React, { useState, useEffect } from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import { ThemeProvider } from "@mui/material/styles";
import theme from "./theme";
import Login from "./components/Login";
import Register from "./components/Register";
import Dashboard from "./components/Dashboard";
import Navbar from "./components/Navbar";
import jwt_decode from "jwt-decode";
import "./App.css"; // Correction du chemin
import Profile from "./Profile";
import Tasks from "./Tasks";
import Auth from "./Auth";
import { API_URL, TOKEN_KEY } from "./constants";
import axios from "axios";

function App() {
  const [token, setToken] = useState(localStorage.getItem(TOKEN_KEY) || null);
  const [userId, setUserId] = useState(null);

  useEffect(() => {
    if (token) {
      const decoded = jwt_decode(token);
      setUserId(decoded.id);
    }
  }, [token]);

  useEffect(() => {
    // Code à exécuter lorsque le DOM est complètement chargé
    console.log("DOM complètement chargé");
  }, []);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get(`${API_URL}/endpoint`);
        console.log(response.data);
      } catch (error) {
        console.error("Erreur lors de la récupération des données :", error);
      }
    };

    fetchData();
  }, []);

  return (
    <ThemeProvider theme={theme}>
      <Router>
        <Navbar />
        <div className="container">
          <header className="header">Défis Informatique</header>
          <Routes>
            {!token ? (
              <>
                <Route
                  path="/login"
                  element={<Login setToken={setToken} setUserId={setUserId} />}
                />
                <Route
                  path="/register"
                  element={
                    <Register setToken={setToken} setUserId={setUserId} />
                  }
                />
              </>
            ) : (
              <>
                <Route
                  path="/"
                  element={<Dashboard token={token} userId={userId} />}
                />
                <Route path="/profile" element={<Profile userId={userId} />} />
                <Route path="/tasks" element={<Tasks userId={userId} />} />
                <Route path="/auth" element={<Auth token={token} />} />
              </>
            )}
          </Routes>
        </div>
      </Router>
    </ThemeProvider>
  );
}

export default App;

Here is my index.html with my src/main.jsx and my src/App.css imported (I tried several possible paths) :

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>React App</title>
</head>
<body>
  <div id="root"></div>
  <link rel="stylesheet" href="/src/App.css">
  <script type="module" src="/src/main.jsx"></script>
</body>
</html>

I also thought it was because of my vite.config.js. Here’s how it looks:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [react()],
  server: {
    host: "0.0.0.0",
    port: 5173,
  },
});

Here is also my app.js on my backend side if you need it for debugging::

const express = require("express");
const app = express();
const userRoutes = require("./routes/users");
const taskRoutes = require("./routes/tasks");
const fs = require("fs");
const https = require("https");

app.use(express.json());

// Routes pour les utilisateurs et les tâches
app.use("/api/users", userRoutes);
app.use("/api/tasks", taskRoutes);

// Route pour la racine
app.get("/", (req, res) => {
  res.send("Bienvenue sur la page d'accueil !");
});

// Démarrer le serveur
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Serveur démarré sur le port ${PORT}`);
});

// Chemins vers les fichiers de certificat et de clé privée
const pathToPrivateKey =
  "D:/Documents/Téléchargements/OpenSSL-Win64/bin/private.key";
const pathToCertificate =
  "D:/Documents/Téléchargements/OpenSSL-Win64/bin/certificate.crt";

// Vérifiez si les fichiers existent
if (fs.existsSync(pathToPrivateKey) && fs.existsSync(pathToCertificate)) {
  const privateKey = fs.readFileSync(pathToPrivateKey, "utf8");
  const certificate = fs.readFileSync(pathToCertificate, "utf8");
  const credentials = { key: privateKey, cert: certificate };

  // Créer un serveur HTTPS
  const httpsServer = https.createServer(credentials, app);

  // Démarrer le serveur sur un port sécurisé (443 ou autre)
  httpsServer.listen(443, () => {
    console.log("HTTPS Server running on port 443");
  });
} else {
  console.error(
    "Les fichiers de certificat ou de clé privée sont introuvables."
  );
}

My problem is that nothing is displayed in localhost:5173 (it gives me "error 404") and nothing is displayed in the console or terminal either

2

Answers


  1. On the frontend side, you are using vite and your index.html file is inside public directory. In vite you CAN’T do this. Your index.html file should be in ROOT directory of the project. see this question

    Login or Signup to reply.
  2. There are two issues in your front-end app.

    1. Using <Router/> two times:
      You have imported the Router already in main.jsx file. You do not need to import it again in App.jsx. Please remove it from App.jsx.

    2. index.html file do not exist in in the root of your project:
      I noticed you shifted your index.html in public folder. It should be placed in the root of your project folder instead. So shift your file from public to root: monteeNiveaux.

    Applying these two changes will fix your issue with front-end project.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search