dronus
dronus

Reputation: 11282

If using nodejs Express .use, why is the path suffix ignored and how to avoid?

If using nodejs package Express, a handler bound by app.use('/intern',handler); is also invoked on pathes like http://host/intern.html.

Why is that, and how to prevent it?

Upvotes: 0

Views: 488

Answers (2)

dronus
dronus

Reputation: 11282

According to the Express developers, .use slices the path on / as well as on . in Express 3.x. This 'feature' was not well documented, and considered bad, and removed by 4.x.

So by using Express 4.x, .use can be used as expected, only matching on / delimited path segments.

Upvotes: 1

Peter Lyons
Peter Lyons

Reputation: 146124

Why is that,

Generally, this is useful as the common case is to want to route all paths beginning with a prefix through the same code. So you could, for example, have an "admin" portion of your site and do something like app.use("/admin", checkUserIsAdmin); to protect that whole set of paths. It's there because prefix matching is more commonly used compared to exact matching.

and how to prevent it?

In your situation, it sounds like you just need to make sure you add your static handler to the app before you add the other route.

app.use(express.static(path.join(__dirname, 'public'));
app.use('/intern', handler); 

If "/intern" is just a single page, use app.get('/intern', handler instead of app.use and that will also solve your collision confusion problem.

Upvotes: 0

Related Questions