我有一个使用Express框架和http-auth模块设计的node.js应用程序,如下所示:
var auth = require('http-auth'); var express = require('express'); // ... var mywebapp = express(); // ... if (usebasicauth) { var basic = auth.basic({realm:"MyRealm", file:"/srv/config/passwd"}); mywebapp.use(auth.connect(basic)); } mywebapp.use('/js', express.static(__dirname + '/files/js')); mywebapp.use('/css', express.static(__dirname + '/files/css')); // ...
但是,我不想保护/js
和/css
目录下可用的资产.这是我尝试做的:
if (usebasicauth) { var basic = auth.basic({realm:"MyRealm", file:"/srv/config/passwd"}); mywebapp.use(function(req, res, next) { if (/^\/(css|js)/.test(req.url)) { next(); } else { auth.connect(basic); } }); }
试图访问的URL下/css
,并/js
达到预期效果; 但是,其他URL永远不会加载.
如何让其他网址按预期工作?
顺序mywebapp.use
很重要.如果你有第一个,mywebapp.use(auth.connect(basic));
那么它将被用于每个请求但是如果你改变顺序它将通过静态并且仅用于它之后的任何东西.
中间件功能按照添加顺序进行处理.
所以下面应该做你想要的.
// no auth for statics mywebapp.use('/js', express.static(__dirname + '/files/js')); mywebapp.use('/css', express.static(__dirname + '/files/css')); // auth reguired from here mywebapp.use(auth.connect(basic));
如果你把mywebapp.use(auth.connect(basic));
它放在express.static之上,那么它也会要求auth.
// auth reguired from here mywebapp.use(auth.connect(basic)); // auth required for statics as well mywebapp.use('/js', express.static(__dirname + '/files/js')); mywebapp.use('/css', express.static(__dirname + '/files/css'));
你也可以做这样的事情https://gist.github.com/gevorg/7168d5f02c1ca5362b2a#file-specific-path-js
// Express module. var express = require('express'); // Authentication module. var auth = require('http-auth'); var basic = auth.basic({ realm: "Simon Area.", file: __dirname + "/../data/users.htpasswd" // gevorg:gpass, Sarah:testpass ... }); // Application setup. var app = express(); app.use(function(req, res, next) { if ('/specific/path' === req.path) { next(); } else { (auth.connect(basic))(req, res, next); } }); // Setup route. app.get('/', function(req, res){ res.send("Hello from express - " + req.user + "!"); }); // Setup guest route. app.get('/specific/path', function(req, res){ res.send("Hello from express - guest!"); }); // Start server. app.listen(1337);