Choosing Between HashRouter and BrowserRouter on the Web

Choosing Between HashRouter and BrowserRouter on the Web

2月 5, 2021 · 1 分钟阅读时长 · 212 字 · -阅读 -评论

In SPA apps, frontend routing typically uses either HashRouter or BrowserRouter. Each has pros and cons. Here’s a summary.

HashRouter vs BrowserRouter

  1. URL form differs: HashRouter uses URL hashes (e.g., https://1991421.cn#posts) while BrowserRouter uses traditional paths (e.g., https://1991421.cn/posts).

  2. BrowserRouter needs some server setup since users may refresh on a deep URL, which hits the server. Ensure all SPA routes serve the host page. HashRouter doesn’t need this.

    app.get('*', function (req, res) {
      res.sendFile(path.join(__dirname + '/index.html'));
    });
    
  3. With HashRouter, in-page anchors can complicate things. For a URL like https://1991421.cn/#posts/detail/1234567#comment, location.hash is #posts/detail/1234567#comment; you’ll need to parse it yourself to get the final anchor.

  4. With HashRouter, the hash portion isn’t included in form submissions.

Conclusion

  • Both have trade-offs. Choose based on needs.
  • If either works, BrowserRouter is generally preferable: no hash-related form/anchor quirks. Just remember the server config.

How SPA Routing Works

  • BrowserRouter uses the HTML5 History API to change URLs and track state.

    • history.pushState pushes a new state into the session history and updates the location bar.
  • HashRouter uses location.hash to change URLs and track state.

    • onhashchange listens for hash changes.

Note: Both are client-side; URL changes don’t reload the page.

Final Thoughts

Frontend routers exist to swap content based on the URL. The routing “registration” mechanism is provided by the frontend—nothing more.

Alan H
Authors
开发者,数码产品爱好者,喜欢折腾,喜欢分享,喜欢开源