I'm trying to use react router v4. The version I'm using is 4.1.1. When the page loads It renders the Home component as it should. But if I navigate to localhost:8080/about
or localhost:8080/test2
, I get this in the browser
Cannot GET /about
My App.jsx
file:
import React from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';
import Home from '../components/Home.jsx';
import Test from '../components/Test.jsx';
const Test2 = () => (
<div>test2 component</div>
);
const App = (props) => (
<BrowserRouter>
<div className="container-fluid">
<Route exact path="/" component={Home} />
<Route path="/about" component={Test} />
<Route path="/test2" render={Test2} />
</div>
</BrowserRouter>
)
export default App;
Webpack config:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './client/index.html',
filename: 'index.html',
inject: 'body'
});
module.exports = {
entry: [
'./client/index.js'
],
output: {
path: __dirname + '/dist',
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.js$/, loader: 'babel-loader', exclude: '/node_modules/'},
{ test: /\.jsx$/, loader: 'babel-loader', exclude: '/node_modules/'}
]
},
plugins: [HtmlWebpackPluginConfig],
devServer: {
contentBase: './dist',
historyApiFallback: true,
}
};
Try adding output.publicPath = '/'
to your config. Here's an example webpack config below which uses ^ and fixes the refresh issue for me. If you're curious "why", this will help.
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './app/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js',
publicPath: '/'
},
module: {
rules: [
{ test: /\.(js)$/, use: 'babel-loader' },
{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ]}
]
},
devServer: {
historyApiFallback: true,
},
plugins: [
new HtmlWebpackPlugin({
template: 'app/index.html'
})
]
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.