Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do routing/navigation in Elm without the # (hash) in the URL?

Tags:

elm

Using the UrlParser.parseHash function i was able to successfully parse the following url:

http://localhost:8000/MyRepl.elm/#home/something-else

The behavior is as expected, when i copy paste this in the browser and hit enter - the app loads with the appropriate view.

But now i want to remove the # and for this i used UrlParser.parsePath function. I kept the rest of the code exactly as before - but for some reason this doesn't work.

When i copy paste this and hit enter:

http://localhost:8000/MyRepl.elm/home/something-else - notice no #.

The browser creates a direct request to the elm -reactor localhost server.

There is no routing happening. The elm reactor server returns a 404 - as if there is no file named /MyRepl.elm/home/something-else

But routing without # should be possible because the http://package.elm-lang.org/packages - Docs site is written in elm and there is no # in the url as you can see.

Questions:

Anyone has experienced the same problem? Any ideas how to fix this?

Or can you point me to a repo where navigation without # works as expected?

like image 443
AIon Avatar asked Nov 27 '16 18:11

AIon


1 Answers

You need a backend that servers your index page for every request. After serving the index page the routing will happen as usual in Elm.

For example in express it would look something like:

router.get('/', function(req, res) {
    res.sendFile(path.join(__dirname, 'public/index.html'));
});

router.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname, 'public/index.html'));
});

Elm reactor doesn't support this.

If you are using webpack you can do the same with the historyApiFallback attribute How to tell webpack dev server to serve index.html for any route

like image 134
Sebastian Avatar answered Sep 22 '22 18:09

Sebastian