简体   繁体   English

从 express 中的路由文件夹访问公共静态文件

[英]Acessing public static files from routes folder in express

I'm trying to access a static 'home.html' file from the public folder.我正在尝试从公共文件夹访问静态“home.html”文件。 The architecture of the app is:该应用程序的架构是:

  • public民众
    • home.html主页.html
  • routes路线
    • index.js索引.js
  • views意见
  • myapp.js我的应用程序

myapp.js: myapp.js:

var express = require('express');
var path = require('path');

var routes = require('./routes/index');

var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);

index.js:索引.js:

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
    res.render('index', { title: 'Express' });
});

router.get('/about', function(req, res, next){
    res.sendFile(__dirname + '/home.html');
});

module.exports = router;

The main problem I'm having is I'm unable to load the home.html file at '/about'.我遇到的主要问题是我无法加载位于“/about”的 home.html 文件。 The "__dirname" in index.js is pointing to the routes folder, and I've tried concatenating '/../' to move up a directory, but I just get a 403 Forbidden Error. index.js 中的“__dirname”指向 routes 文件夹,我尝试连接 '/../' 以向上移动目录,但我只是收到 403 Forbidden Error。 I suppose I could put the home.html file in the routes directory, but I really want to figure out how to solve the underlying problem.我想我可以将 home.html 文件放在路由目录中,但我真的很想弄清楚如何解决根本问题。 Of course, rendering the jade file from the views folder at '/' works perfectly fine.当然,从 '/' 的视图文件夹中渲染 jade 文件效果很好。 Thank you in advance for your help and expertise.预先感谢您的帮助和专业知识。

You are trying to use it in the wrong way.您正试图以错误的方式使用它。 The reason that you get the forbidden error is that the clients shouldn't be able to access folders outside the static folder that you have selected.您收到禁止错误的原因是客户端不应能够访问您选择的静态文件夹之外的文件夹。

What you can do is to select multiple static directories, like Setting up two different static directories in node.js Express framework您可以做的是选择多个静态目录,例如在 node.js Express 框架中设置两个不同的静态目录

Though I recommend that you just place all your publically available files in the same directory.尽管我建议您将所有公开可用的文件放在同一目录中。

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

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