// router.js
const route = (event) => {
event = event || window.event;
event.preventDefault();
window.history.pushState({}, "", event.target.href);
handleLocation();
};
const routes = {
404: "pages/404.html",
"/": "pages/loginPage.html",
"/seller": "pages/sellerPage.html",
"/block-list": "pages/blockListPage.html",
"/customer": "pages/customerPage.html",
};
const handleLocation = async () => {
const path = window.location.pathname;
const route = routes[path] || routes[404];
const html = await fetch(route).then((data) => data.text());
document.getElementById("main-page").innerHTML = html;
};
window.onpopstate = handleLocation;
window.route = route;
handleLocation();
// index.html
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vanilla JS SPA</title>
</head>
<body>
<a href="/" onclick="route()">login</a>
<a href="/seller" onclick="route()">seller</a>
<div id="main-page"></div>
<script src="router.js"></script>
</body>
</html>
I am working on a project using vanilla JavaScript. I want to build a spa router.
If you move the page by clicking a link, the screen is not re-rendered, but if you move the page by directly entering the path,
You will see the message Cannot GET /seller.
This is because I haven’t created a seller.html file, and I want to implement a spa router by showing index.html on every request. How can I do this?