I have a directory structure for a restful express service + Backbone client with pushState enabled like this (client code in public/
)
app.js
lib/routes.js
-- public/
-- index.html
I set up /public
to be a static directory in app.configure
:
app.use(express.static(__dirname + '/public'));
This already works off the bat if the index is visited first.
Then when I directly visit a route other than homepage I ensure to redirect to the index.html
. This works perfectly fine in app.js
, but if I try and put this in lib/routes.js
I get a Forbidden error:
From app.js
works fine:
app.get('*', function(req, res) {
res.sendfile(__dirname + '/public/index.html');
});
From lib/routes.js
:
res.sendfile(__dirname + '../public/index.html');
Gives me:
Error: Forbidden
at SendStream.error (/Users/*****/Sites/myproject/node_modules/express/node_modules/send/lib/send.js:145:16)
at SendStream.pipe (/Users/*****/Sites/myproject/node_modules/express/node_modules/send/lib/send.js:307:39)
at ServerResponse.res.sendfile (/Users/*****/Sites/myproject/node_modules/express/lib/response.js:345:8)
at /Users/*****/Sites/myproject/lib/routes.js:8:7
at callbacks (/Users/*****/Sites/myproject/node_modules/express/lib/router/index.js:164:37)
at param (/Users/*****/Sites/myproject/node_modules/express/lib/router/index.js:138:11)
at pass (/Users/*****/Sites/myproject/node_modules/express/lib/router/index.js:145:5)
at Router._dispatch (/Users/*****/Sites/myproject/node_modules/express/lib/router/index.js:173:5)
at Object.router (/Users/*****/Sites/myproject/node_modules/express/lib/router/index.js:33:10)
at next (/Users/*****/Sites/myproject/node_modules/express/node_modules/connect/lib/proto.js:193:15)
If I simply try:
res.sendfile('/public/index.html');
It can't find the file and I get:
Error: ENOENT, stat '/public/index.html'
To summarise how can I use sendFile
and pass in public/index.html
from lib/routes.js
without getting a Forbidden error?