【问题标题】:Express can't load indexExpress 无法加载索引
【发布时间】:2018-04-26 13:32:54
【问题描述】:

我正在尝试在 aws 上设置我的第一个快速 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)

感谢您的帮助!

【问题讨论】:

    标签: node.js amazon-web-services express


    【解决方案1】:

    路径必须是绝对路径或指定 res.sendFile 的根目录

    您可以使用root 选项:

    res.sendFile('index.html', { root: '.' })
    

    顺便说一句,sendfile 已弃用,请使用sendFile

    【讨论】:

    • 啊,是的,我看到它已被弃用。谢谢!我能够使用 res.sendFile('/web/index.html', { root: '.' }) 并且有效!谢谢!
    猜你喜欢
    • 2014-04-24
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    • 2018-11-29
    • 2015-01-01
    相关资源
    最近更新 更多