i am newbie i am newbie - 28 days ago 7
Javascript Question

cannot GET error 404 on reload?

my react router is working fine with dev env, this is what I did in webpack dev server:

historyApiFallback: {
index: 'index.html',
}


so in production mode I wanted to do the same, I did it in express like this:

const indexPath = path.join(__dirname, '../public/index.html')
const publicPath = express.static(path.join(__dirname, '../public'))

app.use('/public', publicPath)
app.use('/graphql', graphQLHTTP(async (req) => {
let { user } = await getUser(req.headers.authorization);
if(!user) {
user = 'guest'
}
return {
schema,
pretty: true,
graphiql: true,
context: {
user,
}
}
}));

app.get('/', function (_, res) { res.sendFile(indexPath) });


I did not change anything with react-router-dom so I am am assuming the error is in my express config. so what's the equivalent of historyApiFallback in production mode? below is my webpack bundle config:

output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js',
publicPath: '/public/'
},


in my html I reference the bundle like this:

<script type="text/javascript" src="/public/bundle.js"></script>


I think a have the right config but when I reload I get cannot GET Error 404?

Answer Source

You should add this line to your app:

app.get('*', function (_, res) { res.sendFile(indexPath) });

Or you should use this package better: https://github.com/bripkens/connect-history-api-fallback

You should read more about history mode:

To get rid of the hash, we can use the router's history mode, which leverages the history.pushState API to achieve URL navigation without a page reload:

When using history mode, the URL will look "normal," e.g. http://oursite.com/user/id. Beautiful!

Here comes a problem, though: Since our app is a single page client-side app, without a proper server configuration, the users will get a 404 error if they access http://oursite.com/user/id directly in their browser. Now that's ugly.

Not to worry: To fix the issue, all you need to do is add a simple catch-all fallback route to your server. If the URL doesn't match any static assets, it should serve the same index.html page that your app lives in. Beautiful, again!