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)


In here app is an instance of express.


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

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


The path is a URL path

app.get('/', handler);

app.get('/user', handler)

app.get('/post/hello-post', 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'/', (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