Saturday, 30 November 2019

Simple router with url parameter variables

I'm trying to make a simple router with url parameters for id's. eg localhost/profile/123 This works fine but if I remove preventDefault so that the links works 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 works 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()


from Simple router with url parameter variables

No comments:

Post a Comment