1

I have an issue with relative links in express. They appear to be working up to two levels deep and then they stop.

I'll attempt to illustrate the issue I am having.

Viewing page @ http://example.com -> click anchor with href="level-1". This works as expected and links to http://example.com/level-1.

Viewing page @ http://example.com/level-1 -> click anchor with href="level-2". This works as expected and links to http://example.com/level-1/level-2.

Viewing page @ http://example.com/level-1/level-2 -> click anchor with href="level-3". This does NOT work as expected and links to http://example.com/level-1/level-3. I can access http://example.com/level-1/level-2/level-3 using href="level-2/level-3"

I thought it might be the way my routes are organised but no matter what I do to them the behaviour seems to be the same.

Currently I have something like

main.js

...

var app = express();

var routes = require('./router')(app);

router/index.js

module.exports = function(app) {
    app.use('/level-1', require('./routes/level-1'));
    app.use('/', require('./routes/home'));
};

router/routes/level-1.js

var express = require('express');
var router = express.Router();

router.use('/level-2', require('./level-2'));

router.get('/', function(req, res) {
    res.render('level-1');
});
module.exports = router;

router/routes/level-2.js

var express = require('express');
var router = express.Router();

router.use('/level-3', require('./level-3'));

router.get('/', function(req, res) {
    res.render('level-2');
});
module.exports = router;

router/routes/level-3.js

var express = require('express');
var router = express.Router();

router.get('/', function(req, res) {
    res.render('level-3');
});
module.exports = router;

Hopefully I have provided enough information.

Frank-
  • 76
  • 7
  • Anything in [this question](http://stackoverflow.com/questions/5559578/having-links-relative-to-root) relevant? Thought I'd check with this first before speculating. :) – Matthew Bakaitis Sep 15 '14 at 16:46
  • Thanks for replying. I wish it was! I understand how links work themselves. It's express' handling of them that I am a bit foggy on. – Frank- Sep 15 '14 at 17:30
  • Sorry replied before finishing my comment... At the root url they work exactly as I would expect, also on the 'level-1' pages they work exactly as I expect. IE when linking like href="page", page would be appended to the current url. Deeper than level one and this stops happening. – Frank- Sep 15 '14 at 17:38

1 Answers1

0

I figured out the answer to my problem. I had to add the trailing / to anchor links leading to the problem pages.

What threw me, and the reason it was working up to one level deep, was that the first level of pages is accessible from a navigation bar and that links to them all in the style of href="/level-1/", the links from then on are generated and weren't generating with the trailing forward slash so href="level-2".

Frank-
  • 76
  • 7