Node.js 根据文件位置,Node express路由sendfile失败

Node.js 根据文件位置,Node express路由sendfile失败,node.js,express,pushstate,sendfile,Node.js,Express,Pushstate,Sendfile,我有一个restful express service+主干客户机的目录结构,它启用了类似这样的pushState(客户机代码位于public/) 我将/public设置为应用程序中的静态目录。配置: app.use(express.static(__dirname + '/public')); 如果首先访问该索引,则此功能已经可以正常工作 然后,当我直接访问主页以外的路径时,我确保重定向到index.html。这在app.js,中工作得非常好,但是如果我尝试将其放入lib/routes.js

我有一个restful express service+主干客户机的目录结构,它启用了类似这样的pushState(客户机代码位于
public/

我将
/public
设置为
应用程序中的静态目录。配置

app.use(express.static(__dirname + '/public'));
如果首先访问该索引,则此功能已经可以正常工作

然后,当我直接访问主页以外的路径时,我确保重定向到
index.html
。这在
app.js
中工作得非常好,但是如果我尝试将其放入
lib/routes.js
中,我会得到一个禁止的错误:

app.js
运行良好:

app.get('*', function(req, res) {
    res.sendfile(__dirname + '/public/index.html');
});
lib/routes.js

res.sendfile(__dirname + '../public/index.html');
给我:

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)
如果我只是尝试:

res.sendfile('/public/index.html');
它找不到文件,我得到:

Error: ENOENT, stat '/public/index.html'

总结一下如何使用
sendFile
并从
lib/routes.js
传入
public/index.html
而不出现禁止的错误?

谢谢@Joe。为了完整性,因为dupe不是很清楚,并且尝试了各种相对路径,包括尝试
{root:'somepath'}
作为第二个参数不起作用,这就是我所做的:

var path = require('path');
...
app.get('*', function(req, res) {
    res.sendfile(path.resolve('public/index.html'));
});

即使是在
lib/
目录中,它使用基本目录解析,但重新重申相对解析对我来说不起作用,但可能有某种方法可以做到。

可能的重复是因为
。/public/index.html
中的相对路径。看到被骗的人了。
var path = require('path');
...
app.get('*', function(req, res) {
    res.sendfile(path.resolve('public/index.html'));
});