Alex
Alex

Reputation: 8663

Multiple paths for same route function in ExpressJS

I've built a service using Node, Express & Mongoose. At the moment it renders templates to the front-end but I want to extend the functionality to a full API.

I'd like to use a single route for each type of resource to be returned with a flag to tell the server to return API content or to render the view and respond with the HTML.

Examples of this would be as follows:

Both would use the same function (i.e. users.getOne) which would then check if the path api is present and send the correct response accordingly.

I could obviously just do the following:

app.get( '/users/:userId', users.getOne );
app.get( '/api/users/:userId', users.getOne );

and check in the response handler, though I'd rather not have 2 routes defined for each resource.

Upvotes: 3

Views: 1469

Answers (1)

Derek
Derek

Reputation: 967

You can either use Path Patterns or Regular Expressions in your route paths.

Using path patterns your route would look like this:

app.get( '(/api)?/users/:userId', users.getOne );

Upvotes: 6

Related Questions