0% found this document useful (0 votes)
26 views12 pages

Express JS

Express.js is a fast and robust web framework for Node.js that facilitates the development of web and mobile applications by managing servers and routes. It provides features such as middleware for handling HTTP requests, a routing table for defining application endpoints, and various request and response object methods for handling data. Additionally, Express.js supports error handling through middleware functions that can manage errors effectively.

Uploaded by

yash borkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views12 pages

Express JS

Express.js is a fast and robust web framework for Node.js that facilitates the development of web and mobile applications by managing servers and routes. It provides features such as middleware for handling HTTP requests, a routing table for defining application endpoints, and various request and response object methods for handling data. Additionally, Express.js supports error handling through middleware functions that can manage errors effectively.

Uploaded by

yash borkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

 What is Express.

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,

var express = require('express');


var app = express();
app.get('/hello', function(req, res){ res.send("Hello World!"); });
app.listen(3000);

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

 Request Object Methods


Following is a list of some generally used request object methods:
1. req.accepts (types)
This method is used to check whether the specified content types are acceptable,
based on the request's Accept HTTP header field.
Examples:
req.accepts('html');
//=>?html?
req.accepts('text/html');
// => ?text/html?

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"

 Express.js Response Object


The Response object (res) specifies the HTTP response which is sent by an Express
app when it gets an HTTP request.
What it does
● It sends response back to the client browser.
● It facilitates you to put new cookies value and that will write to the client browser
(under cross domain rule).
● Once you res.send() or res.redirect() or res.render(), you cannot do it again,
otherwise, there will be uncaught error.
 Response Object Properties
Index Properties Description
1. res.app It holds a reference to the instance of the express application
that is using the middleware.
2. res.headersSent It is a Boolean property that indicates if the app sent HTTP
headers for the response.
3. res.locals It specifies an object that contains response local variables
scoped to the request

 Response Object Methods


1. Response Append method
Syntax:
res.append(field [, value])
This method appends the specified value to the HTTP response header field. That
means if the specified value is not appropriate then this method redress that.
Examples:
res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);
res.append('Warning', '199 Miscellaneous warning');

2. Response Attachment method


Syntax:
1. res.attachment([filename])
This method facilitates you to send a file as an attachment in the HTTP response.
Examples:
res.attachment('path/to/js_pic.png');

3. Response Cookie method


Syntax:
res.cookie(name, value [, options])
This method is used to set a cookie name to value. The value can be a string or object
converted to JSON.
Examples:
res.cookie('name', 'Aryan', { domain: '.xyz.com', path: '/admin', secure: true });
res.cookie('Section', { Names: [Aryan,Sushil,Priyanka] });
res.cookie('Cart', { items: [1,2,3] }, { maxAge: 900000 });

4. Response ClearCookie method


Syntax:
res.clearCookie(name [, options])
As the name specifies, the clearCookie method is used to clear the cookie
specified by name.
Examples:
To set a cookie
res.cookie('name', 'Aryan', { path: '/admin' });
To clear a cookie:
res.clearCookie('name', { path: '/admin' });

5. Response Download method


Syntax:
res.download(path [, filename] [, fn])
This method transfers the file at path as an "attachment" and enforces the
browser to prompt user for download.
Example:
res.download('/report-12345.pdf');

6. Response End method


Syntax:
res.end([data] [, encoding])
This method is used to end the response process.
Example:
res.end();
res.status(404).end();

7. Response Format method


Syntax:
res.format(object)
This method performs content negotiation on the Accept HTTP header on the
request object, when present.
Example:
res.format({
'text/plain': function(){
res.send('hey');
},
'text/html': function(){
res.send('
hey');
},
'application/json': function(){
res.send({ message: 'hey' });
},
'default': function() {
// log the request and respond with 406
res.status(406).send('Not Acceptable');
}
});

8. Response Get method


Syntax:
res.get(field)
This method provides HTTP response header specified by field.
Example:
res.get('Content-Type');

9. Response JSON method:


Syntax:
res.json([body])
This method returns the response in JSON format.
Example:
res.json(null)
res.json({ name: 'ajeet' })

10. Response JSONP method


Syntax:
res.jsonp([body])
This method returns response in JSON format with JSONP support.
Examples:
res.jsonp(null)
res.jsonp({ name: 'ajeet' })

11. Response Links method


Syntax:
res.links(links)
This method populates the response?s Link HTTP header field by joining the
links
provided as properties of the parameter.
Examples:
res.links({
next: 'http://api.rnd.com/users?page=5',
last: 'http://api.rnd.com/users?page=10'
});

12. Response Location method


Syntax:
res.location(path)
This method is used to set the response location HTTP header field based on the
specified path parameter.
Examples:
res.location('http://xyz.com');

13. Response Redirect method


Syntax:
res.redirect([status,] path)
This method redirects to the URL derived from the specified path, with specified
HTTP status
Examples:
res.redirect('http://example.com');

14. Response Render method


Syntax:
res.render(view [, locals] [, callback])
This method renders a view and sends the rendered HTML string to the client.
Examples:
// send the rendered view to the client
res.render('index');
// pass a local variable to the view
res.render('user', { name: 'aryan' }, function(err, html) {
// ...
});

15. Response Send method


Syntax:
res.send([body])
This method is used to send HTTP response.
Examples:
res.send(new Buffer('whoop'));
res.send({ some: 'json' });
res.send('
.....some html
');

16. Response sendFile method


Syntax:
res.sendFile(path [, options] [, fn])
This method is used to transfer the file at the given path. It sets the Content-Type
response HTTP header field based on the filename's extension.
Examples:
res.sendFile(fileName, options, function (err) {
// ...
});

17. Response Set method


Syntax:
res.set(field [, value])
This method is used to set the response of HTTP header field to value.
Examples:
res.set('Content-Type', 'text/plain');
res.set({
'Content-Type': 'text/plain',
'Content-Length': '123',
})

18. Response Status method


Syntax:
res.status(code)
This method sets an HTTP status for the response.
Examples:
res.status(403).end();
res.status(400).send('Bad Request');

19. Response Type method


Syntax:
res.type(type)
This method sets the content-type HTTP header to the MIME type.
Examples:
res.type('.html'); // => 'text/html'
res.type('html'); // => 'text/html'
res.type('json'); // => 'application/json'
res.type('application/json'); // => 'application/json'
res.type('png'); // => image/png:

 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.

var express = require('express');


var app = express();
app.get('/', function(req, res)
{
var err = new Error("Something went wrong");
next(err); });

/* * other route handlers and middleware here * .... */


app.use(function(err, req, res, next) { res.status(500); res.send("Oops,
something went wrong.") });
app.listen(3000);

You might also like