I know there is a bunch of questions about this but none of them fixed my issue.
I have a react client app with react router <Route path="/login" component={Login} />
and when the user fails to login in my express i have `
app.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true
}))
so the user stays on /login but when the page is refreshed i got the error Cannot GET /login
.
Made a lot of researches in the net and some of them says to create a wildcard route like this:
app.use(express.static(path.join(__dirname, '/client/build')));
app.get('*', (req,res) =>{
res.sendFile(path.join(__dirname, 'client/build/index.html'));
}); // this is below all other routes
Added in webpack.config.dev.js the following code:
devServer: {
historyApiFallback: true
}
But after that i got Unexpected token < in 1.fce49d06.chunk.js:1
in the browser console. After that read about babel-register
to transpile my node code so I created a new file start.js
like this:
require('babel-register')({
presets: [ 'env', 'es2015', 'react' ]
})
require("babel-polyfill")
module.exports = require('./index.js');
Also in the server's package.json i have
"scripts": {
"start": "node start.js",
"server": "nodemon start.js",
"client": "npm run start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\""
},
But still there is Unexpected token <
Any Ideas?
Use connect-history-api-fallback middleware
You can use the connect-history-api-fallback middleware to always fallback to index.html. This can be used in both dev and prod environments.
Use it like this: