简体   繁体   中英

Acessing public static files from routes folder in express

I'm trying to access a static 'home.html' file from the public folder. The architecture of the app is:

  • public
    • home.html
  • routes
    • index.js
  • views
  • 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:

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'. 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. 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. Of course, rendering the jade file from the views folder at '/' works perfectly fine. 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

Though I recommend that you just place all your publically available files in the same directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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