I've got a couple of routes defined, and both work, but only when you follow the flow of the app. Let me explain:
We go to the /first page, and the page renders: a bunch of links to the /second/:id page. You click one of the links and the /second/myID page appears.
OK, so far it's all good.
But then I make a change to the code and in the console I get this error:
GET http://localhost:8081/second/dist/bundle.js
And the network tab shows bundle.js as a 404. If I refresh the page, I get the same weird /second/dist/bundle.js 404.
If I hit the back button, the URL changes to http://localhost:8081/first, but the page won't appear. If I refresh here, the page shows up properly.
Here's my index.js:
class App extends React.Component {
render() {
return (
<BrowserRouter>
<div>
<Route exact path="/" component={Main} />
<Route path="/first"
render={ () => <First
idCards={idCards}
/>
}
/>
<Route path="/second/:id"
render={ ({match}) => {
return (<Second
id={match.params.id}
/>);
}
}
/>
</div>
</BrowserRouter>
);
}
}
Here's my First component:
export default class First extends React.Component {
render() {
return (
<div className="first">
{this.props.idCards.map((card, index) => (
<Second key={index} {...card} />
))}
</div>
);
}
};
Here's the Second component:
export default class Second extends React.Component {
render() {
return (
<h1>{`ID: '${this.props.id}'`}</h1>
);
}
}
And my webpack.config.js:
var path = require('path');
const DEV = process.env.NODE_ENV === 'dev';
const PROD = process.env.NODE_ENV === 'prod';
module.exports = {
devtool: 'source-map',
entry: './src/index.js',
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel-loader'],
exclude: /node_modules/
},{
test: /\.(png|jpg|gif)$/,
loaders: ['url-loader'],
exclude: /node_modules/
},{
test: /\.(css|sass|scss)$/,
use: ['style-loader', 'css-loader?importLoaders=2', 'sass-loader'],
// exclude: /node_modules/
},{
test: /\.(svg)$/,
use: ['file-loader'],
// exclude: /node_modules/
},
{
test: /\.(otf)(\?.*)?$/,
loader: 'url-loader?limit=10000&mimetype=application/font-sfnt'
}]
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/dist/',
filename: 'bundle.js'
}
}
And my question: Why am I getting this weird request for /second/dist/bundle.js?
It's most likely an issue with relative paths in your index.html file for bundle.js
. It works on the home page, because you are already at the root url: /
. But when you refresh on a different page, it thinks that it's at the root and that's why you are getting the 404. It's most likely looking for bundle.js
at localhost/second/dist
instead of localhost/dist
.