Expressjs: sending a file from the parent directory

I would like to use expressjs sendfile to send the file from the parent directory of the script file. I tried to do this:

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

I get a forbidden error because apparently the sendfile does not trust path traversal. So far, I have not been able to figure out how to change the directory of files sent via sendfile. Any clues?

Edit: I was tired when I published this, in fact it is easy. I will leave it here if anyone else stumbles upon this. There is an option parameter for sendfile that allows you to do this, for example:

 app.get( '/', function( req, res ){ res.sendfile('index.html', { root: "../../"}); }); 
+7
source share
3 answers

You should mention root as the second sendfile() parameter.

For example:

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

Here you can find more information: https://github.com/visionmedia/express/issues/1465

+5
source

You need to use express.static .

Say you have the following directory installed:

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

Then you should have the following Express configuration:

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

res.sendfile designed to "thinner" file transfers to the client. See API docs for example .

+2
source

parent folder: -application -routes.js -index.html In the above case, add the following code to route.js to send the file from the parent directory.

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

All Articles