简体   繁体   English

表示父文件夹的访问权限

[英]Express parent folder access

Hi guys I am working on this express aplication. 大家好,我正在研究这种表达方式。 In the top of my express file I wrote this line since all my static files are located in my working directory: 在我的express文件的顶部,我写了这一行,因为我所有的静态文件都位于我的工作目录中:

app.use(express.static(__dirname)); 

Now I want to send a file that exist in a parent folder of the current folder: 现在,我要发送一个存在于当前文件夹的父文件夹中的文件:

app.get('/test', function(req, res) {
res.sendFile("../../test.html");
});

It didn't work for me, Normally because all static files must exist in the directory defind above, Could I make an exception and make my code work? 它对我不起作用,通常是因为所有静态文件都必须存在于上面定义的目录中,我可以做一个例外并使我的代码工作吗?

express.static and res.sendFile don't know anything about each other. express.staticres.sendFile对彼此一无所知。 They happen to share a lot of the same internals but aren't really related. 它们碰巧共享许多相同的内部结构,但并没有真正的关联。

You can put test.html wherever you want and then reference it using Node's built-in path module. 您可以将test.html放在任意位置,然后使用Node的内置path模块对其进行引用。 For example, if your file structure looks like this: 例如,如果您的文件结构如下所示:

test.html
real-app/
├── app.js
├── node_modules/
└── package.json

Then you can send test.html like this: 然后,您可以像这样发送test.html

var path = require('path');

// ...

app.get('/test', function(req, res) {
  var testHtmlPath = path.resolve(__dirname, '..', '..', 'test.html');
  res.sendFile(testHtmlPath);
});

PS: I wouldn't recommend the way you're sending static files. PS:我不建议您使用发送静态文件的方式。 Serving files from the same directory as your app code (which is what __dirname means) can cause code disclosure , which hackers can use to exploit problems in your code. 从与您的应用程序代码相同的目录中提供文件(这是__dirname意思)可能会导致代码泄露 ,黑客可以利用这些信息来利用代码中的问题。 For example, if a hacker visited this URL: 例如,如果黑客访问了该URL:

http://yourapp.com/app.js http://yourapp.com/app.js

They would be able to see app.js , which has all of your application's code. 他们将能够看到app.js ,其中包含您应用程序的所有代码。 You don't want to reveal that to a hacker! 您不想将其透露给黑客! They could also navigate to routes like /secret-passwords.json or other similar files. 他们还可以导航到/secret-passwords.json类的/secret-passwords.json或其他类似文件。

Typically, static files are placed into a special directory, often called static or public . 通常,静态文件放置在一个特殊目录中,通常称为staticpublic You can serve files from this directory like this: 您可以从以下目录提供文件:

var path = require('path');

// ...

var staticFilesPath = path.resolve(__dirname, 'public');
app.use(express.static(staticFilesPath));

In general, you should be pretty careful about sending files that live outside of your app's code. 通常,在发送应用程序代码之外的文件时,您应该非常小心。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM