Javascript 带有URL参数变量的简单路由器

Javascript 带有URL参数变量的简单路由器,javascript,url,single-page-application,url-parameters,Javascript,Url,Single Page Application,Url Parameters,我正在尝试用ID的URL参数制作一个简单的路由器。e、 g.localhost/profile/123这可以正常工作,但是如果我删除preventDefault使链接正常工作,或者刷新浏览器,或者直接转到同一URL,它不工作,浏览器在localhost/profile中查找javascript文件main.js,而不是原始localhost。没有参数的路由工作正常。这里发生了什么 const router = async path => { if(!path) path = loca

我正在尝试用ID的URL参数制作一个简单的路由器。e、 g.
localhost/profile/123
这可以正常工作,但是如果我删除
preventDefault
使链接正常工作,或者刷新浏览器,或者直接转到同一URL,它不工作,浏览器在
localhost/profile
中查找javascript文件
main.js
,而不是原始
localhost
。没有参数的路由工作正常。这里发生了什么

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()
const路由器=异步路径=>{
如果(!path)path=location.pathname
常量段=路由分割('/'))
路径=“/”+段[1]
常量参数=段[2]
常数路由={
“/”:{handler:home},
'/about':{handler:about},
“/profile”:{handler:profile},
}
渲染(html)`
${wait routes[path].handler(参数?参数:“”)}
`,document.body)
}
常量main=async()=>{
等待路由器()
document.body.addEventListener('click',e=>{
e、 预防默认值()
如果(e.target&&e.target.nodeName==“A”){
让path=e.target.pathname
history.pushState({urlPath:path}',location.origin+path)
onpopstate=()=>路由器()
路由器(路径)
}
})
}
main()

您需要服务器端URL重写来处理URL的直接加载。至于从错误的路径加载
main.js
,在引用资产时需要使用绝对路径,例如
而不是
复制//等。对于使用历史推送状态路由的任何东西,这个问题总是会出现。谢谢!因为这是一个副本,我将删除它。