1

I made a simple react router. When I was developing it I was using npm start command which started a developing server. And everything were working. But when I built my app with command npm run build (using webpack), launched a simple http server and went to /add_project there is a 404 error. And I don't know why does it happen. Help please!

Here is the code:

App.js

imports...

render() {
    return (
        <Switch>
            <div>
                <Route exact path='/' component={Projects}/>
                <Route exact path='/add_project' component={AddProject} />
            </div>
        </Switch>
    );
}}

index.js

imports...

ReactDOM.render(
    <BrowserRouter>
        <App />
    </BrowserRouter>,
    document.getElementById('root')
);

webpack.config.js

const HtmlPlugin = require('html-webpack-plugin')

module.exports = {
  entry: './src',
  output: {
    filename: 'app.js',
    path: __dirname + '/dist'
  },
  devtool: 'source-map',
  module: {
    loaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'babel-loader'
    }]
  },
  plugins: [
    new HtmlPlugin({
      template: 'public/index.html'
    })
  ]
}

UPD:

package.json

{
  "name": "Test",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "build": "webpack -p --progress --config webpack.config.js",
    "dev-build": "webpack --progress -d --config webpack.config.js",
    "test": "echo \"Error: no test specified\" && exit 1",
    "watch": "webpack --progress -d --config webpack.config.js --watch",
    "start": "react-scripts start"
  },
  "license": "MIT",
  "babel": {
    "presets": [
      "es2015",
      "react"
    ]
  },
  "devDependencies": {
    "babel-core": "^6.25.0",
    "babel-loader": "^7.0.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "bootstrap": "^4.0.0",
    "css-loader": "^0.28.4",
    "eslint": "^4.18.1",
    "eslint-plugin-react": "^7.7.0",
    "extract-text-webpack-plugin": "^2.1.2",
    "file-loader": "^0.11.2",
    "jquery": "^3.2.1",
    "react": "^15.6.1",
    "react-bootstrap": "^0.31.0",
    "react-dom": "^15.6.1",
    "react-router-dom": "^4.2.2",
    "style-loader": "^0.18.2",
    "webpack": "^3.11.0"
  }
}

UPD2:

AddProject.js

import React, { Component } from 'react';

class AddProject extends Component {
  constructor()
  {
    super();
  }

  render() {
    return (
      <form className="form-horizontal">
        <input type="text" ref="title" className="input" />
        <input type="text" ref=""/>
      </form>
    );
  }
}

export default AddProject;

1 Answers1

0

You are already matching an exact path with '/' then matching it again with your /add_project route. Try changing

     <Route exact path='/add_project' component=
       {AddProject} />

To

      <Route path='/add_project' component=
       {AddProject} />

If exact is set on parent route the child route does not match, but 404 is rendered as expected

radlaz
  • 228
  • 2
  • 14