【问题标题】:expressjs: Sending a file from parent directoryexpressjs:从父目录发送文件
【发布时间】:2012-10-31 11:56:17
【问题描述】:

我想使用 expressjs 的 sendfile 从脚本文件的父目录发送文件。我试图做的是:

app.get('/', function(req, res){
    res.sendfile('../../index.html');
});

我收到一个禁止错误,因为显然 sendfile 不信任路径遍历。到目前为止,我一直无法弄清楚如何更改通过 sendfile 发送的文件的目录。有什么提示吗?

编辑:发这个的时候有点累,其实挺简单的。我会把它留在这里,以防其他人偶然发现。 sendfile 有一个选项参数可以让你这样做,就像这样:

app.get( '/', function( req, res ){
    res.sendfile('index.html', { root: "../../"});
});

【问题讨论】:

  • 服务器上的静态资源也可以使用express.static。理想情况下,sendFile 函数用于提供文件(客户端下载文件)而不是用于静态内容。

标签: javascript express sendfile


【解决方案1】:

sendfile() 的第二个参数必须提到 root。

例如:

app.get('/:dir/:file', function(req, res) {
  var dir = req.params.dir,
      file = req.params.file;

  res.sendfile(dir + '/' + file, {'root': '../'});
});

您可以在此处找到更多详细信息: https://github.com/visionmedia/express/issues/1465

【讨论】:

    【解决方案2】:

    您需要使用express.static

    假设您设置了以下目录:

    /app
       /buried
           /deep
               server.js
       /public
           index.html
    

    那么你应该有以下 Express 配置:

    var express = require('express');
    var server = express.createServer();
    server.configure(function(){
        server.use(express.static(__dirname + '../../public'));
    });
    server.listen(3000);
    

    res.sendfile 用于将文件“细粒度”传输到客户端。 See API docs for example.

    【讨论】:

    • Express 3 中似乎不存在configure 方法
    【解决方案3】:

    父文件夹: -应用程序 -routes.js -index.html 在上述情况下,将以下代码添加到 routes.js 以从父目录发送文件。

    var path=require("path") //assuming express is installed 
    
    app.get('/', function(req, res){
    res.sendFile(path.join(__dirname + '/../index.html'));
    });
    

    【讨论】:

      猜你喜欢
      • 2021-09-14
      • 2019-01-29
      • 1970-01-01
      • 1970-01-01
      • 2013-05-22
      • 2013-05-25
      • 1970-01-01
      • 1970-01-01
      • 2014-08-23
      相关资源
      最近更新 更多