B
B
brainexplosion2018-08-09 14:19:38
React
brainexplosion, 2018-08-09 14:19:38

Why doesn't routing work?

Route not working. Writes: "Cannot GET /login". I use react+webpack. Tell me the reason please. Here is a part of the code (where, in my opinion, may be the cause of the error):

import React, { Component } from 'react';
import { BrowserRouter as Router, Route } from "react-router-dom";
import Signup from "./Signup"
import Login from "./Login"
import SecretComponent from './SecretComponent';

class App extends Component {

    render() {
        return (
            <Router>
                <div>
                    <Route exact path="/" component={Signup} />
                    <Route path="/login" component={Login} />
                    <Route path="/secretpage" component={SecretComponent} />
                </div>
            </Router>
        );
    }
}

export default App;

{
  "name": "react_webpack_starter",
  "version": "1.0.0",
  "description": "Boilerplate for React apps",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --mode development --open --hot",
    "build": "webpack --mode production"
  },
  "author": "Brad Traversy",
  "license": "MIT",
  "dependencies": {
    "axios": "^0.18.0",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-router-dom": "^4.3.1"
  },
  "devDependencies": {
    "@babel/plugin-proposal-class-properties": "^7.0.0-beta.56",
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.4",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-preset-env": "^1.6.1",
    "babel-preset-es2016": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^0.28.11",
    "html-webpack-plugin": "^3.1.0",
    "style-loader": "^0.20.3",
    "webpack": "^4.4.0",
    "webpack-cli": "^2.0.13",
    "webpack-dev-server": "^3.1.1"
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-08-09
@brainexplosion

The problem is that you use and change someone else's solution without really understanding how it even works. As a result, look for the cause in the wrong place. You have a server, webpack dev server in your case, only handles '/'.
Add the following lines to the config:

module.exports = {
  /* ... */
  output: {
     /* ... */
    publicPath: '/'
  },
   /* ... */
  devServer: {
    historyApiFallback: true,
  },
};

Instead of adding a devServer block, you can change the start script in package.json:
Documentation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question