Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

reactjs - React Router v4: Cant load page on GitHub pages

Locally I can browse to /buttons just fine I can even refresh it and its fine too, but when I upload the build directory to github pages I can't access /buttons and instead I get the GitHub 404 page, not my own 'notfound' page.

If I make a link from the home page to /buttons, then buttons will load, but browsing there directly it does not load.

import React, { useState } from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import { Context } from "./components/context";
import { Layout } from "./components/layout";
import { Home } from './routes/home';
import { Buttons } from './routes/buttons';
import { NotFound } from './routes/notfound';

const Router: React.FC = () => {

  const [global, setGlobal] = useState({
    language: localStorage.getItem("language") || 'en',
    apiUrl: 'https://api.domain.com/api',
    loggedIn: localStorage.getItem("jwt") ? true : false,
    redirectUrl: '',
    modal: false,
    modalState: '',
  });

  return (
    <Context.Provider value={{ global, setGlobal }}>
      <BrowserRouter basename={process.env.PUBLIC_URL}>
        <Route render = {({ location }) => (
          <Layout location = { location }>
            <Switch location = { location }>
              <Route exact path = '/' component = { Home } />
              <Route exact path = '/buttons/' component = { Buttons } />
              <Route component = { NotFound }/>
            </Switch>
          </Layout>
        )} />
      </BrowserRouter>
    </Context.Provider>
  );
}
export { Router };

In package.json I do have the homepage defined as:

"homepage": "https://myName.github.io/myRepo",

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As per deployment docs at https://create-react-app.dev/, for GH pages:

GitHub Pages doesn’t support routers that use the HTML5 pushState history API under the hood (for example, React Router using browserHistory). This is because when there is a fresh page load for a url like http://user.github.io/todomvc/todos/42, where /todos/42 is a frontend route, the GitHub Pages server returns 404 because it knows nothing of /todos/42.

If you want to add a router to a project hosted on GitHub Pages, here are a couple of solutions:

  • You could switch from using HTML5 history API to routing with hashes. If you use React Router, you can switch to hashHistory for this effect, but the URL will be longer and more verbose (for example, http://user.github.io/todomvc/#/todos/42?_k=yknaj) Read more about different history implementations of react-router.

Change your routing from:


    <BrowserRouter basename={process.env.PUBLIC_URL}>
      <Route render = {({ location }) => (
         <Layout location = { location }>
             <Switch location = { location }>
                <Route exact path = '/' component = { Home } />
                <Route exact path = '/buttons/' component = { Buttons } />
                <Route component = { NotFound }/>
              </Switch>
           </Layout>
       )} />
    </BrowserRouter>

To:

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

...


    <HashRouter basename={process.env.PUBLIC_URL}>
      <Route render = {({ location }) => (
         <Layout location = { location }>
             <Switch location = { location }>
                <Route exact path = '/' component = { Home } />
                <Route exact path = '/buttons/' component = { Buttons } />
                <Route component = { NotFound }/>
              </Switch>
           </Layout>
       )} />
    </HashRouter>
...

  • Alternatively, you can use a trick to teach GitHub Pages to handle 404 by redirecting to your index.html page with a special redirect parameter. You would need to add a 404.html file with the redirection code to the build folder before deploying your project, and you’ll need to add code handling the redirect parameter to index.html. You can find a detailed explanation of this technique in this guide.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...