我正在尝试在 AWS 上设置我的第一个 Express Web 服务器。如果我尝试简单地使用“res.send”,我可以让 hello world 显示在端口 9000 上,但是我的下面的代码会产生错误,我相信它与我的目录结构有关,但我似乎无法找出正确的方法的写法。我的 server.js 文件位于名为 home/server/server.js 的文件夹内,但是我尝试加载的索引文件位于 home/web/index.html 内。我该如何编写它才能正确加载。这是我的代码:
var express = require('express');
var app = express();
app.get('/', function (req, res){
res.sendfile(__dirname + './../web/index.html')
//res.send('Hello there, world!\n');
});
var port = 9000;
app.listen(port);
console.log('Listening on port', port);
这是我当前收到的错误:
ForbiddenError: Forbidden
at SendStream.error (/home/ubuntu/home/node_modules/send/index.js:270:31)
at SendStream.pipe (/home/ubuntu/home/node_modules/send/index.js:554:12)
at sendfile (/home/ubuntu/home/node_modules/express/lib/response.js:1099:8)
at ServerResponse.res.sendfile (/home/ubuntu/home/node_modules/express/lib/response.js:498:3)
at ServerResponse.eval [as sendfile] (eval at wrapfunction (/home/ubuntu/home/node_modules/depd/index.js:410:22), <anonymous>:4:11)
at /home/ubuntu/home/server/server.js:30:9
at Layer.handle [as handle_request] (/home/ubuntu/home/node_modules/express/lib/router/layer.js:95:5)
at next (/home/ubuntu/home/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/ubuntu/home/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/ubuntu/home/node_modules/express/lib/router/layer.js:95:5)
感谢您的帮助!
最佳答案
path must be absolute or specify root to res.sendFile
您可以使用root
选项:
res.sendFile('index.html', { root: '.' })
顺便说一句,sendfile
已弃用,请使用 sendFile
。
关于node.js - Express无法加载索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50032521/