Languages
[Edit]
EN

Express.js - routers

0 points
Created by:
Krzysiek
741

In this article, we would like to show you how to use routers in Express.js.

Introduction

Edit

Normally, we define routes in Express.js using the following syntax:

Where:

  • httpMethod is one of the following requests:
    • GET
    • POST
    • PUT
    • PATCH
    • DELETE
  • path is the route at which the request will run.

Practical example:

Now, when we run the application and go to the localhost:5000/users we get the following result:

Node.js / Express.js - HTTP GET method example result
Node.js / Express.js - HTTP GET method example result

We can also define multiple different methods (such as GET, POST... ) for the same route.

Example:

To easy maintain the application we need to separate the routes dedicated for users from our main index.js file. To do so we will use express.Router.

Routers

Edit

1. The first thing we need to do is create a new directory called routes and a file for our users routes - users.js. The project structure should now look as follows:

2. Inside the users.js file, import express.Router and move the users requests from index.js to it.

users.js file:

Note:

Notice that now we use router instead of app and we don't write '/users' in the request path. We will specify it later in the index.js file.

3. Import the router inside index.js file and specify the route.

Now the app.use() function call on route '/users' attaches the users router with this route. Whatever requests our app gets at the '/users', will be handled by our users.js router. The '/' route in users.js file is actually a subroute of '/users'.

Run the app and go to the http://localhost:5000/users to see the result.

Result:

Node.js / Express.js - result for HTTP GET method using express.Router
Node.js / Express.js - result for HTTP GET method using express.Router
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join