gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 23:30:53 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com