Express JS routing

📆 Last updated Sep 03, 2019 👷 By, Chandan Tudu
Express JS routing

In this tutorial you will learn about Express JS Routing.

What is Express JS routing

Routing is used to determine how an application responds to a client request to a particular URL and a specific HTTP request method such as GET, POST, PUT, etc.


How to define an Express route

Structure of a route

app.method(path, handler)

app:

In here app is an instance of express.


method:

The method is an HTTP request method and method name should be lower case.

app.get(path, handler);
app.post(path, handler);
app.put(path, handler);
app.delete(path, handler);

path:

The path is a URL path

http://localhost:3000
app.get('/', handler);

http://localhost:3000/user
app.get('/user', handler)

http://localhost:3000/post/hello-post
app.get('/post/hello-post', handler)


handler:

The handler is a function and it is executed when the root matched.

app.get('/', (req, res) => {
    res.send('Home page from get request')
});

open http://localhost:3000/ through get request

Browser Output
Home page

app.post('/', (req, res) => {
    res.send('Home page from post request')
});

open http://localhost:3000/ through post request

Browser Output
Home page from post request

Next isExpress JS Route Handler

Previous is – Install express and write your first app with the express

Leave a Reply

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