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?
Thanks @Joe. For completeness since the dupe isn't very clear and trying various relative pathing including trying {root: 'somepath'} as 2nd param didn't work this is what I did:
var path = require('path');
...
app.get('*', function(req, res) {
res.sendfile(path.resolve('public/index.html'));
});
Even though that is in the lib/ directory it resolved using the base directory, to re-reiterate relative resolving didn't work for me but there may be some way of doing it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With