node.js 在 Express 中对所有路径使用特定的中间件,但特定路径除外

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12921658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:29:23  来源:igfitidea点击:

Use specific middleware in Express for all paths except a specific one

node.jsroutesexpressmiddleware

提问by Thomas

I am using the Express framework in node.js with some middleware functions:

我在 node.js 中使用 Express 框架和一些中间件功能:

var app = express.createServer(options);
app.use(User.checkUser);

I can use the .usefunction with an additional parameter to use this middleware only on specific paths:

我可以使用.use带有附加参数的函数来仅在特定路径上使用此中间件:

app.use('/userdata', User.checkUser);

Is it possible to use the path variable so that the middleware is used for all paths except a specific one, i.e. the root path?

是否可以使用路径变量,以便中间件用于除特定路径之外的所有路径,即根路径?

I am thinking about something like this:

我在想这样的事情:

app.use('!/', User.checkUser);

So User.checkUseris always called except for the root path.

SoUser.checkUser总是被调用,除了根路径。

回答by chovy

I would add checkUser middleware to all my paths, except homepage.

我会将 checkUser 中间件添加到我的所有路径中,除了主页。

app.get('/', routes.index);
app.get('/account', checkUser, routes.account);

or

或者

app.all('*', checkUser);

function checkUser(req, res, next) {
  if ( req.path == '/') return next();

  //authenticate user
  next();
}

You could extend this with underscore to search for the req.path in an array of non-authenticated paths:

您可以使用下划线对其进行扩展,以在未经身份验证的路径数组中搜索 req.path:

function checkUser(req, res, next) {
  var _ = require('underscore')
      , nonSecurePaths = ['/', '/about', '/contact'];

  if ( _.contains(nonSecurePaths, req.path) ) return next();

  //authenticate user
  next();
}

回答by jsalonen

Instead of directly registering User.checkUseras middleware, register a new helper function, say checkUserFilter, that gets called on every URL, but passed execution to userFiled` only on given URLs. Example:

不是直接注册User.checkUser为中间件,而是注册一个新的辅助函数,例如checkUserFilter,在每个 URL 上调用,但仅在给定的 URL 上将执行传递给 userFiled`。例子:

var checkUserFilter = function(req, res, next) {
    if(req._parsedUrl.pathname === '/') {
        next();
    } else {
        User.checkUser(req, res, next);
    }
}

app.use(checkUserFilter);

In theory, you could provide regexp paths to app.use. For instance something like:

理论上,您可以提供到app.use. 例如类似的东西:

app.use(/^\/.+$/, checkUser);

Tried it on express 3.0.0rc5, but it doesn't work.

在 express 3.0.0rc5 上尝试过,但不起作用。

Maybe we could open a new ticketand suggest this as a feature?

也许我们可以开一张新票并建议将此作为一项功能?

回答by Jonatan Lundqvist Medén

You can set the middleware on each route also.

您也可以在每个路由上设置中间件。

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
  if (!req.body) return res.sendStatus(400)
  res.send('welcome, ' + req.body.username)
})

回答by user1872904

Use

app.use(/^(\/.+|(?!\/).*)$/, function(req, resp, next){...

This pass any url apart from /. Unless, it works for me.

这会传递除 / 之外的任何 url。除非,它对我有用。

In general

一般来说

/^(\/path.+|(?!\/path).*)$/

(see How to negate specific word in regex?)

(请参阅如何否定正则表达式中的特定单词?

Hope this helps

希望这可以帮助

回答by Abhay Shiro

Use this library called express-unless

使用这个名为express-unless 的

Require authentication for every request unless the path is index.html.

除非路径是 index.html,否则要求对每个请求进行身份验证。

app.use(requiresAuth.unless({
  path: [
    '/index.html',
    { url: '/', methods: ['GET', 'PUT']  }
  ]
}))

Path it could be a string, a regexp or an array of any of those. It also could be an array of object which is URL and methods key-pairs. If the request path or path and method match, the middleware will not run.

Path 它可以是字符串、正则表达式或其中任何一个的数组。它也可以是一个对象数组,它是 URL 和方法密钥对。如果请求路径或路径与方法匹配,则中间件将不会运行。

This library will surely help you.

这个图书馆肯定会帮助你。