Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router + webpack, sub routes not working

I am trying to set up my routers for my app, and have the basic / entry point working (seemingly). It seems when I try to start adding sub routes, it is breaking. I have a pretty straight forward set up right now. I am using react + redux and my render looks like :

 ReactDOM.render(
<Provider store={store}>
     <Router history={browserHistory} >
        <Route path="/" component={comp1.Component}>
            <Route path="test" component={comp2.Component} />
        </Route>
    </Router>
</Provider>,
// eslint-disable-next-line no-undef
document.getElementById('app')
);

I am running webpack dev server on localhost:8080, and it serves the first route with no problem, however when I go to localhost:8080/test, I am getting a Cannot GET /test .

Here is my webpack config:

var path = require('path');
var webpack = require('webpack');

module.exports = {
  devtool: 'eval',
  entry: [
    'webpack-dev-server/client?http://localhost:3000',
    'webpack/hot/only-dev-server',
    './client/app.jsx'
  ],
  output: {
    path: path.join(__dirname, ''),
    filename: 'bundle.js',
    publicPath: '/'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.optimize.DedupePlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production')
    }),
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    })
  ],
   module: {
    loaders: [{
      test: /\.jsx?$/,
      exclude: /node_modules/,
      loader: "babel-loader",
      include: __dirname,
      query: {
        presets: [ 'es2015', 'react', 'react-hmre' ]
      }
    }]
  }
}

Unsure what I am doing wrong here, would be grateful for any help. Thanks!

like image 747
ajmajmajma Avatar asked Oct 14 '16 19:10

ajmajmajma


1 Answers

React Router uses the HTML5 history API. This means that 404 responses need to serve /index.html.

The docs mention how this works. You need to add this to your module.exports object:

devServer: {
  historyApiFallback: true
}

Note that this only works for the CLI, when using the Node.js API you need to add this as a second parameter:

var server = new WebpackDevServer(compiler, { historyApiFallback: true });
like image 138
spacek33z Avatar answered Sep 23 '22 02:09

spacek33z