节点表达app.get(“/ ..”父目录无效

时间:2016-08-08 02:22:55

标签: node.js express

  1. ./core/server.js
  2. ./core/index.html
  3. ./core/styles.css
  4. ./bin/init-transpiled.js
  5. 如何在index.htmllocalhost:8000/core仍然可以访问相对路径index.html../bin/init-transpiled的情况下托管./styles.css

2 个答案:

答案 0 :(得分:1)

您可以像这样托管index.html文件。

app.get('/', function(req, res) {
    res.sendFile(path.resolve(__dirname + "/index.html"));
});

您需要在服务器配置中将bin文件夹设置为静态文件夹,以便从客户端访问bin文件夹文件。

app.use(express.static(path.resolve(__dirname + '/../bin')));   

然后在index.html中,您可以像这样访问您的文件。

<script src="../bin/init-transpiled.js">

请注意,如果索引使用./styles.css,则需要使用../core/styles.css

答案 1 :(得分:0)

app.use('/', express.static(__dirname));
app.use('/', express.static(__dirname + '/../'));
app.get('/', function (req, res) {
    res.sendFile(__dirname + "/index.html");
});

使用'/'

  1. 静态托管此目录(例如,用于访问本地./styles.css
  2. 静态托管父目录(否则您无法遍历../bin/
  3. 发送index.html作为回复。
  4. 注意: '/'不是必需的,默认为'/',您可以将中间件处理函数编写为第一个参数< / p>

    请参阅Express Docs - static files