使用快递服务静态文件时无法使用基本身份验证 [英] Cannot use basic authentication while serving static files using express

查看:243
本文介绍了使用快递服务静态文件时无法使用基本身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Node.js的Express框架,我试图提供包含在目录中的静态文件,同时对其进行基本身份验证。当我这样做时,我会提示输入用户名和密码(如预期),但是在我输入正确后,我被赋予了一个404。如果我删除身份验证并提供相同的目录,我实际上会得到这些页面包含在其中。

Using the Express framework for node.js, I'm trying to serve up static files contained in a directory while also putting basic authentication on it. When I do so, I am prompted for the username and password (as expected), but after I correctly enter them, I'm given a 404. If I remove the authentication check and serve up the same directory, I actually get the pages contained within it.

这是一个快速的服务器,作为概念证明:

Here's a quick server I whipped up as a proof-of-concept:

var express = require('express');

var app = express();

var auth = express.basicAuth(function(user,pass) {
  return 'user' === user && 'pass' === pass;
});

app.use('/admin', auth, express.static(__dirname + '/admin'));
app.use('/adminNoAuth', express.static(__dirname + '/admin'));

app.listen(8082);

当我点击 localhost:8082 / admin 我得到用户名/密码,然后是一个404.当我点击 localhost:8082 / adminNoAuth 它的页面。

When I hit localhost:8082/admin I get the username/password, then a 404. When I hit localhost:8082/adminNoAuth it serves up the page.

我使用Express 3.4.7和node.js 0.10.22。

I'm using Express 3.4.7 and node.js 0.10.22.

推荐答案

app.use 不让你以这种方式连接中间件。各种 app.VERB 功能,但 app.use 不。这是一个中间件一次。

app.use doesn't let you chain middlewares in that way. The various app.VERB functions do, but app.use doesn't. That's for one middleware at a time.

如果您将2个中间件分成单独的电话,您应该获得所需的结果:

If you split the 2 middlewares out into separate calls, you should get the results you want:

app.use('/admin', auth)
app.use('/admin', express.static(__dirname + '/admin'));

编辑

作为快递版本 4.x 您可以将多个中间件作为数组传递,或将参数或两者的混合传递到 app.use 。现在可以使静态文件授权安全:

As of express version 4.x you can pass in multiple middlewares as an array, or arguments, or mixture of both into app.use. Making static files authorization safe would now be:

app.use( "/admin", [ auth, express.static( __dirname + "/admin" ) ] );

但是两种方法仍然完全有效。

But both ways are still perfectly valid.

这篇关于使用快递服务静态文件时无法使用基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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