Basics of Routes
Basics of Routes
Express
Topics to be covered
Definitio
Synta
Request and Response object in Expres
Routing
Handling success and erro
Example of an E-commerce application
Definition
In an Express application, routes define how the application responds to client requests for specific URLs and
HTTP methods. A route consists of a combination of an HTTP method (such as GET, POST, PUT, DELETE, etc.)
and a URL pattern, which together determine which handler function should be executed to generate a
response.
In Express, we can define routes using the app.METHOD() functions, where METHOD is the HTTP method name
(e.g., get, post, put, delete, etc.). Each of these functions takes two arguments: the URL pattern to match and
the handler function to execute.
Syntax
Each route can have one or more handler functions, which are executed when the route is matched.
app.METHOD(PATH, HANDLER)
where
`app` is an instance of express (assume instance of express name as `app
METHOD is an HTTP request method, in lowercase i.e get, post, delete, put, patch, and so on
PATH is a URL path on the serve
HANDLER is the callback function executed when the route is matched
In Express.js, the request method is used to retrieve information from an HTTP request sent to the server. It is
represented by the `req` object that is available in the callback function of an Express route handler.
Some of the most frequently used request properties and methods are as follows
`req.para s This property is an object that contains properties mapped to the named route
m ` -
parameters. or example, if you have a route ` users :userId`, you can access the userId parameter using
F / /
req.params.userId.
`req.body` - This property contains the parsed request body sent by the client in the HTTP request. This is
typically used for POST, PUT, and PATCH requests where data is sent in the request body. For example, you
can access the ‘name’ pass in the body by `const {name} = req.body
`req.headers` - This property is an object that contains the HTTP headers sent by the client in the request.
Example - `console.log(req.headers)`, this will log the `req.headers` which is a key value map where each
is a header name and each value corresponds to the value of the header. Some common headers include
‘user-agent’, ‘accept`, and ‘content-type
`req.cookies` - This property is an object that contains the cookies sent by the client in the request.
Cookies object can be accessed using `req.cookies` Example - to access the value of the “myCookie”
cookie “req.cookies.myCookie” can be used to access it
`req.get(header)` - This method is used to retrieve the value of a specific HTTP header in the
request. Example, to retrieve the value of the User-Agent header, you can use `req.get('User-Agent')
`req.ip` - This property contains the IP address of the client that sent the request.
Example -
console.log(req.ip)
// => '127.0.0.1
`req.path` - This property contains the path part of the URL of the request.
Example -
// example.com/users?sort=desc
console.dir(req.path)
`req.method` - This property contains the HTTP method used by the request, such as GET, POST, PUT, etc.
Example
console.log(req.method)
// => GET
Response object
In Express.js, the response object (res) is used to send a response to the client that sent the HTTP request.
The res object provides a variety of methods that can be used to send different types of responses, such
as HTML pages, JSON data, and error messages.
res.send() - This method sends a string, buffer, JSON object, or an HTML file as the response.
Example
// send
res.send("hello world")
Example
res.json({
success: true,
})
res.render() - This method renders an HTML view using a template engine like EJS or Handlebars.
Example
res.render("index")
Example
// redirect to google.com
res.redirect('http://google.com')
Example
res.download(filePath, fileName)
Example
res.sendFile(filePath);
Example
// cookie with name myCookie with maxm,httpOnly & secure options
res.cookie('name', 'myCookie', {
httpOnly: true,
secure: true
})
Example
res.clearCookie(myCookie)
Routing
Routing in Express.js involves several parts that work together to handle incoming HTTP requests and
generate appropriate responses. Here are the main parts of routing in Express.js
Route methods - Express.js supports several HTTP methods, such as GET, POST, PUT, DELETE, and others,
which are used to define routes that handle requests of a specific type. You define these methods using
Ex ample -
// GET method
res.send('Hello world')
})
Route paths - Route paths, in combination with a request method, define the endpoints at which requests
can be made. Route paths can be strings, string patterns, or regular expressions.
Ex ample -
// path or endpoints
res.send('about')
})
Route Handlers - The route handler is a callback function that executes when the server receives a
request matching the HTTP method and route path. This function can perform various tasks, such as
sending a response, rendering a view, or forwarding the request to other middleware.
Ex ample -
})
Route Parameters - Route parameters are named URL segments that are used to capture the values
specified at their position in the URL. The captured values are populated in the `req.params` object, with
the name of the route parameter specified in the path as their respective keys.
Example -
// Routes with route parameters
res.send(req.params)
})
Using the `res.status()` method to set the HTTP status code the `res.send()` or `res.json()` method to send
the response data.
Example -
if (users.length === 0) {
// handling error
res.status(200).json([])
} else {
// handle success
res.status(200).json({users})
})
/**
The curly braces around `users` are shorthand for `{users:users}`, which creates
an object with a property named `users` whose value is the `users` array.
**/
Example -
try {
if (user) {
// handle success
return res.status(200).json({
success: true,
user,
});
} catch (error) {
// handling error
res.status(500).json({
success: false,
});
};
res.json(news);
})
The above code is the example of an Express route that responds to an HTTP GET request to the URL (“/
newsfeeds”).
When a GET request is made to the URL(“/newsfeeds”), the callback function specified in the second
argument will be called. In this case, the function simply sends
The app instance is used to define the route, which is created by calling the express() function. The
app.get() method is used to define a route for the HTTP GET method and the URL ("/newsfeeds"). The second
argument to app.get() is a callback function that is called when a GET request is made to the URL. The req
object contains information about the incoming request, while the res object sends a response object back
to the client.
// perform logic...
})
})
Respond to a POST request on the route (/newsfeed), the application’s home page.
})