javascript expressjs:从父目录发送文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13337288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
expressjs: Sending a file from parent directory
提问by Silvester
I would like to use expressjs's sendfile to send a file from a parent directory of the script file. What I tried to do is this:
我想使用 expressjs 的 sendfile 从脚本文件的父目录发送文件。我试图做的是这样的:
app.get('/', function(req, res){
res.sendfile('../../index.html');
});
I get a forbidden error because apparently, sendfile does not trust path traversal. So far I've been unable to figure out how to change the directory for files sent via sendfile. Any hints?
我收到一个禁止的错误,因为很明显,sendfile 不信任路径遍历。到目前为止,我一直无法弄清楚如何更改通过 sendfile 发送的文件的目录。任何提示?
Edit: I was kind of tired when posting this, in fact it is kind of easy. I'll leave it here in case anybody else stumbles upon this. There's an option parameter for sendfile that allows you to do just that, like so:
编辑:发帖时我有点累,实际上这很容易。我会把它留在这里以防其他人偶然发现。sendfile 有一个选项参数可以让您做到这一点,如下所示:
app.get( '/', function( req, res ){
res.sendfile('index.html', { root: "../../"});
});
采纳答案by Marius Craciunoiu
You have to mention root as the second parameter of sendfile()
.
你必须提到 root 作为 的第二个参数sendfile()
。
For example:
例如:
app.get('/:dir/:file', function(req, res) {
var dir = req.params.dir,
file = req.params.file;
res.sendfile(dir + '/' + file, {'root': '../'});
});
You can find more details here: https://github.com/visionmedia/express/issues/1465
您可以在此处找到更多详细信息:https: //github.com/visionmedia/express/issues/1465
回答by Corey Gwin
You need to use express.static
.
您需要使用express.static
.
Say you have the following directory set up:
假设您设置了以下目录:
/app
/buried
/deep
server.js
/public
index.html
Then you should have the following Express configuration:
那么你应该有以下 Express 配置:
var express = require('express');
var server = express.createServer();
server.configure(function(){
server.use(express.static(__dirname + '../../public'));
});
server.listen(3000);
res.sendfile
is meant for "finer-grain" transferring of files to the client. See API docs for example.
res.sendfile
用于将文件“细粒度”传输到客户端。例如,请参阅 API 文档。
回答by Sree Durga M
parent folder: -app -routes.js -index.html In the above case, Add the following code to routes.js to send a file from parent directory.
父文件夹:-app -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'));
});