How to handle relative paths in node.js / express?
Asked Answered
S

1

6

I've written a website in node.js and express. Now I configured lighttpd to use the node.js server with an subdirectory:

$HTTP["url"] =~ "^/app/" {
  proxy.server  = ( "" => ( (
                              "host" => "127.0.0.1",
                              "port" => 3000
                            ) )
                  )
}

When I open http://localhost/app/ I get error 404 because I wrote something like this:

app.get('/', function (req, res){
  res.render('index');
});

Is there a better way as modifying these lines like:

var relPath = '/app';

app.get(relPath + '/', function (req, res){
  res.render('index');
});

?

Streeto answered 7/7, 2012 at 23:31 Comment(5)
app.use('/app', app.router); may do the trick.Vacuity
It does in fact do the trick, though I'm not running behind a proxy.Becquerel
The proxy shouldn't matter as long it doesn't munge the path.Vacuity
@RyanOlds Your comment should be the accepted answer!Herod
any chance of getting a full code block on how the app.use('/app', app.router); fits into the above example?Paillasse
S
4

As Ryan commented the solution is:

app.use('/app', app.router);

If you use e.g. express.static or express.favicon you have to tell app.use the path also:

app.use('/app', express.favicon(__dirname + '/public/images/favicon.ico'));
app.use('/app', express.static(__dirname + '/public'));

Remember to write '/app' before each internal link you set in your html.

Streeto answered 6/1, 2013 at 0:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.