我想通过将用户重定向回索引来保护文件夹及其内容。
我已经尝试过这个,但它只能部分起作用。
var express = require('express');
var path = require('path');
var http = require('http');
var app = express();
app.set('port', 8080);
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'views')));
app.get('/', function(req, res) {
res.render('index.ejs');
});
app.get('/protected/*', function(req, res, next) {
res.redirect('/');
next();
});
//activating server
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
例如,此路由“localhost:8080/protected”和“localhost:8080/protected/asdf”,但不路由“localhost:8080/protected/otherPage.html”。
在这种情况下,asdf 不是实际文件,但 otherPage.html 是。因此,如果文件存在,则不会重定向,但如果不存在,则重定向。这是为什么?
最佳答案
处理静态文件的行 app.use(express.static(path.join(__dirname, 'views')));
出现在 app.get('/protected' 之前)
所以它首先被匹配。
如果您将静态处理程序移到代码的后面,这将按照您的要求工作。
但是,我建议将静态项目拆分到一个单独的文件夹中,以防止意外泄露您可能包含在 View 文件夹中的 ejs 文件中的任何服务器端代码。
关于javascript - 路由整个文件夹及其内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40447358/