Express.js Routing

Express.js Routing

In this tutorial you will learn about express routing.

What is express 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

app.get('/hello', (req, res) => {
    res.send('Hello World!')
});

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

Browser Output
Hello World!

Posts Navigation