node.js - Express无法加载索引

标签 node.js amazon-web-services express

我正在尝试在 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/

相关文章:

javascript - 已到达字符串末尾,但未找到右括号 : NodeJS & Jade

amazon-web-services - AWS CloudFront 误解路由规则并将资源重定向回 S3 存储桶对象 URL

javascript - 非常基本的 React + NodeJS 获取 : Why is my response not what I want?

Node.js - 扩展 res.render 的 Expressjs 中间件

node.js - Express 在处理第一个 API 时不向第二个 API 提供服务

Javascript:将日期转换为 UTC 格式

javascript - 全局 npm 包在 Ubuntu 上的安装位置

javascript - 请求中包含的安全 token 无效。 AWS 开发工具包

amazon-web-services - 无法使用 Kong Ingress Controller 后面的 keycloak 访问管理控制台页面

mysql - 对两列值组合的唯一约束