且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

仅通过Express框架对某些URL使用HTTP基本身份验证

更新时间:2023-02-26 12:47:36

mywebapp.use的顺序很重要. 如果您有第一个mywebapp.use(auth.connect(basic));,则它将用于每个请求 但是,如果您更改顺序,则它将传递静态信息,并且仅用于其后的内容.

The order of mywebapp.use is important. If you have first mywebapp.use(auth.connect(basic)); then it will be used for every request but if you change the order it will pass statics and be only used for whatever is after it.

按照添加顺序对中间件功能进行处理.

所以下面应该做你想要的.

So following should do what you want.

// 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认证.

If you place mywebapp.use(auth.connect(basic)); above express.static it will reguire auth for it as well.

// 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'));