ExpressJs Creating Routes
Syntax
app.METHOD(PATH, HANDLER)
Where:
app
is an instance of theexpress
module.METHOD
is an HTTP request method.PATH
is a path on the server.HANDLER
is a function that handles the request and generates the response.
Example
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.post('/', (req, res) => {
res.send('Got a POST request')
})
app.put('/user', (req, res) => {
res.send('Got a PUT request at /user')
})
app.delete('/user', (req, res) => {
res.send('Got a DELETE request at /user')
})
app.listen(3000, () => {
console.log('Example app listening on port 3000!')
})
Explanation
In ExpressJs
, routes are used to handle different requests made to the server. The app.METHOD()
function creates a route and specifies the HTTP request method to be handled.
The PATH
argument specifies the path to be matched, and the HANDLER
argument is a function that generates the response for the request.
In the example above, we have defined four different routes for the HTTP methods GET
, POST
, PUT
and DELETE
. When a request is made to the server with the corresponding HTTP method and path, the respective handler function is called to generate the response.
Use
Routes in ExpressJs
are used to handle different types of requests made to the server. They can be used to serve HTML files, handle form submissions, and generate JSON responses.
Important Points
ExpressJs
routes are created using theapp.METHOD()
function.- The
METHOD
argument specifies the HTTP request method to be handled. - The
PATH
argument specifies the path to be matched. - The
HANDLER
argument is a function that generates the response for the request. - Routes can be used to handle different types of requests made to the server.
- Multiple routes can be defined for the same path and different HTTP methods.
Summary
In this article, we have learned how to create routes in ExpressJs
. We have seen the syntax for defining routes and the different HTTP request methods that can be used. We have also looked at an example of defining routes for GET
, POST
, PUT
and DELETE
methods, and generating responses using handler functions.