Categories
JavaScript Answers

How to set default path (route prefix) in Express?

Spread the love

Sometimes, we want to set default path (route prefix) in Express.

In this article, we’ll look at how to set default path (route prefix) in Express.

How to set default path (route prefix) in Express?

To set default path (route prefix) in Express, we can create a Router instance.

For instance, we write

const router = express.Router();
router.use("/user", user);

app.use("/api/v1", router);

to call express.Router to create a router.

Then we call router.use with a user route object.

Next, we call app.use with router to use the router in the app.

Therefore, we access the routes in the user router by prepending /api/v1/user to the URL.

Conclusion

To set default path (route prefix) in Express, we can create a Router instance.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *