简体   繁体   中英

react v6 routing - Refresh (F5) page returns 404 page not found

The issue I'm encountering concerns a basic react app (v6). More specifically it is related to routing. I've gone through several questions/answers on stackoverflow already but wasn't able to figure out what's wrong.

Here's what I'm working with.

App.js

import "./App.css";
import React from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import NavBar from "./components/NavBar";
import Home from "./pages/Home";
import About from "./pages/About";
import PrivacyPolicy from "./pages/PrivacyPolicy";
import TermsOfService from "./pages/TermsOfService";

const App = () => {

  return (
    <BrowserRouter>         
      <NavBar/>        
      <Routes>
        <Route path="/" element = {<Home/>} />
        <Route path="/home" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/privacyPolicy" element={<PrivacyPolicy />} />
        <Route path="/termsOfService" element={<TermsOfService />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
  
ReactDOM.render(
    <App />,
  document.getElementById('root')
);

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="./favicon.ico" /> <!-- Used to be "%PUBLIC_URL%/favicon.ico" >> might be required when live -->
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta name="description" content="Genesis platform for financial education." />
    <meta name="keywords" content="Genesis" class="next-head" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <title>Genesis</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root">
    </div>
  </body>
</html>

And here is the error message when pressing the F5 (refresh) button in a browser window. 找不到页面 - 反应

The buttons in the NavBar work well to navigate to the different pages, but the refresh leaves me hanging... From the research I've done I feel like the solution is somewhere within these files, but I just can't figure out what to change.

In SPAs, you need to send all the traffic to index.html. You can do it by adding a _redirects file in the root folder and add this:

/*    /index.html   200

In the server, this serves index.html to all the requests, and React handles the routing in the browser.

If you used CRA for this, put the _redirects file in the public folder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM