5

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()
Ahmad Yazji
  • 566
  • 6
  • 16
georgesamper
  • 4,989
  • 5
  • 40
  • 59
  • 3
    You need server-side URL rewriting to handle direct loading of URLs. As for loading `main.js` from the wrong path, you need to use absolute paths when referencing assets, eg ` – Phil Nov 27 '19 at 22:51
  • 1
    Duplicate of [React-router urls don't work when refreshing or writing manually](https://stackoverflow.com/questions/27928372/react-router-urls-dont-work-when-refreshing-or-writing-manually) / [Vue Router return 404 when revisit to the url](https://stackoverflow.com/questions/36399319/vue-router-return-404-when-revisit-to-the-url) / etc. This problem comes up all the time for anything that uses history push-state routing – Phil Nov 27 '19 at 22:56
  • Ok thanks! Since this is a duplicate I'll delete it. – georgesamper Nov 28 '19 at 13:14

0 Answers0