I'm trying to make a simple router with URL parameters for IDs. e.g. localhost/profile/123
This works fine but if I remove preventDefault
so that the links work as normal, or refresh the browser, or go directly to that same URL, it does not work and the browser looks for the javascript file main.js
in localhost/profile
instead of the origin localhost
. Routes without parameters work fine. What is happening here?
const router = async path => {
if(!path) path = location.pathname
const segment = route.split('/')
path = '/' + segment[1]
const parameter = segment[2]
const routes = {
'/' : { handler: home },
'/about' : { handler: about },
'/profile' : { handler: profile },
}
render(html`
<main>${await routes[path].handler(parameter ? parameter : '')}</main>
`, document.body)
}
const main = async () => {
await router()
document.body.addEventListener('click', e => {
e.preventDefault()
if(e.target && e.target.nodeName == "A") {
let path = e.target.pathname
history.pushState({urlPath: path}, '', location.origin + path)
onpopstate = () => router()
router(path)
}
})
}
main()