在Express和Node.js中限制到静态文件的路由 [英] Restricting route to static files in Express and Nodejs

查看:225
本文介绍了在Express和Node.js中限制到静态文件的路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试将路由限制为尚未登录的用户.我的主要问题是,即使我使用get方法定义页面,例如:

I am currently trying to restrict the routes to users who haven't been logged. My main issue is that even if I define a page with a get method such as:

 app.get('/alpha/information', isLoggedIn,
        function(req, res){
            res.sendFile(path.join(__dirname + '/alpha/pages/Example.html'));
        });

用户可以仅将URL编辑为:http://localhost:3000/alpha/pages/Example.html并访问该页面.现在,我已经阅读了关于SO的几个类似问题,但是找不到答案.我受到启发的是: Q1 第二季度 Q3 .但是,我无法找到解决问题的方法.

The user can sill just edit the url to: http://localhost:3000/alpha/pages/Example.html and access the page. Now I have read several similar questions on SO but I cannot find the answer. Some of which I was inspired were: Q1,Q2, Q3. Nonetheless I was unable to find a solution to my issue.

我当前的文件结构是: FileStructureLink

My current file structure is: FileStructureLink

我正在尝试限制对 Example.html,ExampleTwo.html blabla.html

我正在使用此代码来设置请​​求,但我想它们可能不合适:

I am using this code to set up the requests but I guess they might not be right:

app.use(express.static(path.join(__dirname, 'Alpha')));
app.use(express.static(path.join(__dirname, '/')));
app.use('/', express.static(__dirname + '/login.html'));

app.use('/', express.static(__dirname + '/login.html'));专门用于将默认的localhost:3000/加载为localhost:3000/login

This app.use('/', express.static(__dirname + '/login.html')); specifically is used to make the default localhost:3000/ load as localhost:3000/login

如何在不为每个静态html文件编写路由的情况下限制对所有静态html文件的访问?

How can I restrict access to all the static html files without having to write a route for each of them?

中间件功能:

function isLoggedIn(req, res, next) {
        console.log('here is Authenticated', req.isAuthenticated())
        if (req.isAuthenticated()){
            return next();
        }
        res.redirect('/login');
    }

推荐答案

您可以通过在其上附加其他中间件来限制快速静态中间件.

You can restrict your express static middleware, by attaching another middleware to it.

var express = require("express");
var path = require( "path" );
var app = express();

function isLoggedIn( req, res, next ) {
   console.log("trying restricted file");
   next();
}

app.use( '/Alpha', isLoggedIn, express.static( path.join( __dirname, 'Alpha' ) ) );
app.use( express.static( path.join( __dirname, 'anonymous' ) ) );

app.listen( 3000 );

每次调用localhost:3000/restricted/*时,都将通过isLoggedIn函数执行此操作.

By doing this every time you call localhost:3000/restricted/* will via isLoggedIn function.

根据您的文件结构修改了代码.

Code modified, according to your file structure.

这篇关于在Express和Node.js中限制到静态文件的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆