Express JS
Express JS
js
Express.js is a web framework for Node.js. It is a fast, robust and asynchronous in nature.
Express is a fast, assertive, essential and moderate web framework of Node.js.
You can assume express as a layer built on the top of the Node.js that helps manage a
server and routes. It provides a robust set of features to develop web and mobile
applications.
It can be used to design single-page, multi-page and hybrid web applications.
It allows to setup middlewares to respond to HTTP Requests.
It defines a routing table which is used to perform different actions based on HTTP
method and URL.
It allows to dynamically render HTML Pages based on passing arguments to
templates.
Why use Express
Ultra fast I/O
Asynchronous and single threaded
MVC like structure
Robust API makes routing easy
Routing :- How an application endpoint respond to client request.
The following function is used to define routes in an Express application
app.method(path, handler)
This METHOD can be applied to any one of the HTTP verbs – get, set, put, delete. An
alternate method also exists, which executes independent of the request type.
Path is the route at which the request will run.
Handler is a callback function that executes when a matching request type is found on the
relevant route. For example,
If we run our application and go to localhost:3000/hello, the server receives a get request
at route "/hello", our Express app executes the callback function attached to this route
and sends "Hello World!" as the response.
HTTP request and responses :-
Express.js Request Object
Express.js Request and Response objects are the parameters of the callback
function which is used in Express applications. The express.js request object
represents the HTTP request and has properties for the request query string,
parameters, body, HTTP headers, and so on.
Syntax:
app.get('/', function (req, res) {
// --
})
Express.js Request Object Properties
1. req.app This is used to hold a reference to the instance of the express
application that is using the middleware.
2. req.baseurl It specifies the URL path on which a router instance was
mounted.
3. req.body It contains key-value pairs of data submitted in the request body. By
default, it is undefined, and is populated when you use body-parsing
middleware such as body-parser.
4. req.cookies When we use cookie-parser middleware, this property is an object
that contains cookies sent by the request.
5. req.fresh It specifies that the request is "fresh." it is the opposite of req.stale.
6. req.hostname It contains the hostname from the "host" http header.
7. req.ip It specifies the remote IP address of the request.
8. req.ips When the trust proxy setting is true, this property contains an array of
IP addresses specified in the ?x-forwarded-for? request header.
9. req.originalurl This property is much like req.url; however, it retains the
original request URL, allowing you to rewrite req.url freely for internal
routing purposes.
10. req.params An object containing properties mapped to the named route ?
parameters?. For example, if you have the route /user/:name, then the "name"
property is available as req.params.name. This object defaults to {}.
11. req.path It contains the path part of the request URL.
12. req.protocol The request protocol string, "http" or "https" when requested with
TLS.
13. req.query An object containing a property for each query string parameter in
the route.
14. req.route The currently-matched route, a string.
15. req.secure A Boolean that is true if a TLS connection is established.
16. req.signedcookies When using cookie-parser middleware, this property
contains signed cookies sent by the request, unsigned and ready for use.
17. req.stale It indicates whether the request is "stale," and is the opposite of
req.fresh.
18. req.subdomains It represents an array of subdomains in the domain name of
the request.
19. req.xhr A Boolean value that is true if the request's "x-requested-with" header
field is "xmlhttprequest", indicating that the request was issued by a client
library such as jQuery
2. req.get(field)
This method returns the specified HTTP request header field.
Examples:
req.get('Content-Type');
// => "text/plain"
req.get('content-type');
// => "text/plain"
req.get('Something');
// => undefined
3. req.is(type)
This method returns true if the incoming request's "Content-Type" HTTP header
field matches
the MIME type specified by the type parameter.
Examples:
// With Content-Type: text/html; charset=utf-8
req.is('html');
req.is('text/html');
req.is('text/*');
// => true
4. req.param(name [, defaultValue])
This method is used to fetch the value of param name when present.
Examples:
// ?name=sasha
req.param('name')
// => "sasha"
// POST name=sasha
req.param('name')
// => "sasha"
// /user/sasha for /user/:name
req.param('name')
// => "sasha"
Middleware :-
Middleware functions are functions that have access to the request object (req),
the response object (res), and the next middleware function in the application’s request-
response cycle. These functions are used to modify req and res objects for tasks like
parsing request bodies, adding response headers, etc.
var express = require('express');
var app = express();
app.use(function(req, res, next){
console.log("A new request received at " + Date().now());
next(); });
app.listen(3000);
Output
Now open localhost:3000.
The above middleware is called for every request on the server. So after every request, we
will get the following message in the console of nodemon −
A new request received at 1737448050745
To restrict it to a specific route (and all its subroutes), provide that route as the first
argument of app.use(). For Example,
var app = express();
app.use('/things', function(req, res, next)
{ console.log("A request for things received at " + Date.now());
next(); });
app.get('/things', function(req, res){ res.send('Things'); });
app.listen(3000);
Error Handling :-
Error handling in Express is done using middleware. But this middleware has special
properties. The error handling middleware are defined in the same way as other
middleware functions, except that error-handling functions MUST have four
arguments instead of three – err, req, res, next. For example, to send a response on any
error, we can use –
app.use(function(err, req, res, next)
{ console.error(err.stack);
res.status(500).send('Something broke!'); });
For error handling, we have the next(err) function. A call to this function skips all
middleware and matches us to the next error handler for that route. Let us understand this
through an example.