Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

node.js - Use specific middleware in Express for all paths except a specific one

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

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

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

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.checkUser is always called except for the root path.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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 to search for the req.path in an array of non-authenticated paths:

function checkUser(req, res, next) {
  const nonSecurePaths = ['/', '/about', '/contact'];
  if (nonSecurePaths.includes(req.path)) return next();

  //authenticate user
  next();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...