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:3000app.get('/', handler);
http://localhost:3000/userapp.get('/user', handler)
http://localhost:3000/post/hello-postapp.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
app.post('/', (req, res) => {
res.send('Home page from post request')
});
open http://localhost:3000/
through post request
Next is – Express JS Route Handler
Previous is – Install express and write your first app with the express