node.js - Node 快速路由发送文件失败取决于文件位置

标签 node.js express pushstate sendfile

我有一个 restful express 服务的目录结构 + 像这样启用了 pushState 的 Backbone 客户端(public/ 中的客户端代码)

app.js
lib/routes.js
-- public/
   -- index.html

我在 app.configure 中将 /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 而不会出现 Forbidden 错误?

最佳答案

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

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

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

关于node.js - Node 快速路由发送文件失败取决于文件位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22900510/

相关文章:

LetsEncrypt 证书的 Android WebView "Trust anchor for certification path not found"

jquery - History.pushState() 未显示正确的 URL

javascript - 后退按钮只能工作一次

node.js - 让 Node.js 使用 http_proxy、https_proxy 和 no_proxy 环境变量

javascript - 使用 Node.js + Express,无需模板引擎

javascript - 如何在没有 Node.js 的情况下使用 JS require()

javascript - 我应该如何在没有cookie和外部模块的情况下在nodejs中创建多语言

javascript - 从 Url Javascript 中删除附属查询字符串

node.js - 限制 mongoDB 聚合中不同类型结果的数量

node.js - 服务器不断运行更新缓存的功能,它会阻止所有其他服务器功能吗?