When writing SPA applications, we face the problem of 404 error when refreshing a page, aside of course for the root page 'index.html', which really exists.
Let's see how we can solve this problem.
Here a piece of code which handles routes in a SPA (here I use Preact)
function Routage() {
return (
<Router onChange={handleRoute}>
<Home path="/" />
<ScanPage path="/scanpage" />
<Query path="/queryall" />
<About path="/about" />
</Router>
);
}
export default Routage;
The path '/' redirect automatically to an actual html page which is 'index.html'.
The other paths have no corresponding 'html' pages. That's why we get a 404 error when we access them directly.
So what can we do ?
Well, if those pages does not exist, let us create each of them !
Here we will then create the folowing pages:
- scanpage.html
- queryall.html
- about.html
In each page we will insert the following html code :
for example in the about.html)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="0;URL='/?page=about'">
</head>
</html>
Do the same for the other pages.
In the index.html page put the following code :
<script>
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
window.page = urlParams.get('page');
</script>
And in you Router page put the following :
const handleRoute = async e => {
if(window.page) {
route(`/${window.page}`);
window.page = null;
}
};
function Routage() {
return (
<Router onChange={handleRoute}>
<Home path="/" />
<ScanPage path="/scanpage" />
<Query path="/queryall" />
<About path="/about" />
</Router>
);
}
That's it .
Now every time, you refresh a page, or access it directly, you will be redirected to the correct 'page' without any 404 error :-).
Of course, you will have to adapt according the framework (or no) you use, but the idea is still valid.
If you have any advices, I will appreciate..