Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to make a Single Page Application using html, css and javascript. I would like to add some routing to it. I have made server-side rendered websites with nodejs and express. How do I create a routing system for my SPA? Can we use express for client-side routing? If not, are there any alternatives to express for client side routing?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
699 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you don't want to use a framework/library for building a SPA, you have two options

  1. Use a JS routing library ex: navigo, didn't try it myself TBH
  2. Build it by yourself

To build your own simple SPA Routing, first, you need to:

  • Define routing config, each path with the relevant component/element/content to load
  • Define your routing root, the element where you will inject the content

Then you have two options:

  1. Use # Hash paths (ex: domain.com/#/messages) with window popstate event, so you can handle this event by getting the hash path and decide which content to inject in the root, check this answer for more details about his approach
  2. Implement a custom routing with normal paths (ex: domain.com/messages), that needs more effort, and to achieve that you need to:
  • Implement your custom navigation links, where you need to prevent the default behavior of navigation, and do the navigation manually using your custom logic
  • Use History API, (ex. pushState) to control the location state and the history stack
  • Adjust your server config to always load index.html
  • Add your custom logic using the Location API to manage these redirects manually, ie. when a user opens domain.com/messages, it will open index.html, then you need to check manually what the content to load for /messages path and inject it in the root element

Please be aware of the needed time, effort, reliability, maintainability, of each option before starting!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...