When updating the page, it writes "Cannot GET /login" - BrowserRouter from react-router-dom

I made a test of the route on the react:

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";

ReactDOM.render(
    <Router>
        <Switch>
            <Route exact path="/" render={()=>{
                return (
                    <div>
                        <h1>Home page</h1>
                        <Link to="/login">Go to Login</Link>
                    </div>
                );
            }}/>
            <Route path="/login" render={()=>{
                return (
                    <div>
                        <h1>Login page</h1>
                        <Link to="/">Go to Home</Link>
                    </div>
                );
            }}/>
        </Switch>
    </Router>,
    document.getElementById("index")
);

Everything works beautifully if you just run it. But I get the message "Cannot GET /login" instead of viewing the Login page, if I go to the "/login" page just at the address (or refresh the page while on this page) after going to this page from the "Home page".

I found an example of "BrowserReact", opened the solution separately, and everything works fine there.

On an older version the reactor and the router solved the problem by placing the compiled js at the desired addresses.

Is this the normal behavior of BrowserRouter? Or do I misunderstand something, because the example I found works correctly?

Author: Stanislav, 2018-05-24

4 answers

Maybe it will help someone: adding the following code to webpack.config helped me.js

devServer: {
    historyApiFallback: true,
}
 1
Author: hersir1, 2019-10-11 18:27:47

The problem is most likely in the webpack-dev-sever server.

Surprisingly, the problem was solved on another server (from create-react-app react-scripts start). But again, the solution worked only after I completely removed node&npm, as well as the installed dependencies, and installed them again. Before the complete removal of node&npm, for some reason, this server did not want to work.

 0
Author: Stanislav, 2018-05-25 03:45:41

I'll leave it as a reminder to myself. Same webpack4 problem It was solved by adding the line publicPath: '/', in webpack. config.js


module.exports = {
  entry: path.join(paths.SRC, 'index.jsx'),
  output: {
    path: paths.DIST,
    publicPath: '/',
    filename: 'bundle.js'
  },

 0
Author: BeZ Cepera, 2019-07-09 09:35:34

If you are working on your own build, do not forget to write in Webpack. config:

devServer: {
    historyApiFallback: true,
}
 0
Author: Denys, 2020-05-18 15:39:40