匹配 url 模式的 Node.js

Ata*_*sad 4 url-pattern node.js express

我需要在简单的 node.js 中等效于以下 express.js 代码,我可以在中间件中使用它。我需要根据 url 进行一些检查,并希望在自定义中间件中进行。

app.get "/api/users/:username", (req,res) ->
  req.params.username
Run Code Online (Sandbox Code Playgroud)

到目前为止,我有以下代码,

app.use (req,res,next)->
  if url.parse(req.url,true).pathname is '/api/users/:username' #this wont be true as in the link there will be a actual username not ":username" 
    #my custom check that I want to apply
Run Code Online (Sandbox Code Playgroud)

rob*_*lep 5

一个技巧是使用这个:

app.all '/api/users/:username', (req, res, next) ->
  // your custom code here
  next();

// followed by any other routes with the same patterns
app.get '/api/users/:username', (req,res) ->
  ...
Run Code Online (Sandbox Code Playgroud)

如果您只想匹配GET请求,请使用app.get代替app.all

或者,如果你只想在某些特定的路由上使用中间件,你可以使用这个(这次在 JS 中):

var mySpecialMiddleware = function(req, res, next) {
  // your check
  next();
};

app.get('/api/users/:username', mySpecialMiddleware, function(req, res) {
  ...
});
Run Code Online (Sandbox Code Playgroud)

编辑另一个解决方案:

var mySpecialRoute = new express.Route('', '/api/users/:username');

app.use(function(req, res, next) {
  if (mySpecialRoute.match(req.path)) {
    // request matches your special route pattern
  }
  next();
});
Run Code Online (Sandbox Code Playgroud)

但我看不出这比app.all()用作“中间件”的效果如何。