Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 41

Express

What is Express?
• It’s a web framework that let’s you structure a
web application to handle multiple different
http requests at a specific url.
• Express is a minimal, open source and flexible
Node.js web app framework designed to make
developing websites, web apps & API’s much
easier.
• Consider the node.js code
• var http = require('http'); // Import Node.js core module
• var server = http.createServer(function (req, res) { //create web server
• if (req.url == '/') { //check the URL of the current request

• }
• else if (req.url == "/student") {

• }
• else if (req.url == "/admin") {

• }
• else
• res.end('Invalid Request!');
• });
• server.listen(5000); //6 - listen for any incoming requests
• console.log('Node.js web server at port 5000 is running..')
• Consider the server created using express,
• Code Explanation:
• In our first line of code, we are using the require function to include the
"express module."
• Before we can start using the express module, we need to make an
object of it.
• Here we are creating a callback function. This function will be called
whenever anybody browses to the root of our web application which
is http://localhost:3000 . The callback function will be used to send the
string 'Hello World' to the web page.
• In the callback function, we are sending the string "Hello World" back to
the client. The 'res' parameter is used to send content back to the web
page. This 'res' parameter is something that is provided by the 'request'
module to enable one to send content back to the web page.
• We are then using the listen to function to make our server application
listen to client requests on port no 3000. You can specify any available
port over here.
• You can clearly see that we if browse to the URL of localhost on port
3000, you will see the string 'Hello World' displayed on the page.
Why use Express?
• The express framework is the most common framework used for developing Node js
applications. The express framework is built on top of the node.js framework and
helps in fast-tracking development of server-based applications.
• Routes are used to divert users to different parts of the web applications based on
the request made. The response for each route can be varied depending on what
needs to be shown to the user.
• Templates can be used to inject content in an efficient manner. Jade is one of the
most popular templating engines used in Node.js applications.

 
• Following are some of the core features of Express framework −
• Allows to set up middlewares to respond to HTTP Requests.
• Defines a routing table which is used to perform different actions based on HTTP
Method and URL.
• Allows to dynamically render HTML Pages based on passing arguments to templates.
•  
Advantages of Express.js
• Makes Node.js web application development fast and easy.
• Easy to configure and customize.
• Allows you to define routes of your application based on HTTP
methods and URLs.
• Includes various middleware modules which you can use to
perform additional tasks on request and response.
• Easy to integrate with different template engines like Jade, Vash,
EJS etc.
• Allows you to define an error handling middleware.
• Easy to serve static files and resources of your application.
• Allows you to create REST API server.
• Easy to connect with databases such as MongoDB, Redis, MySQL
RESTful Web Services
• A web service is a collection of open protocols and standards used
for exchanging data between applications or systems. Software
applications written in various programming languages and running
on various platforms can use web services to exchange data over
computer networks like the Internet in a manner similar to inter-
process communication on a single computer. This interoperability
(e.g., communication between Java and Python, or Windows and
Linux applications) is due to the use of open standards.
• Web services based on REST Architecture are known as RESTful web
services. These webservices uses HTTP methods to implement the
concept of REST architecture. A RESTful web service usually defines
a URI, Uniform Resource Identifier a service, which provides
resource representation such as JSON and set of HTTP Methods.
A RESTful web service request contains :
•An Endpoint URL. An application implementing a RESTful API
will define one or more URL endpoints with a domain, port, path,
and/or querystring — for example, https://mydomain/user/123?
format=json.
•The HTTP method. Differing HTTP methods can be used on any
endpoint which map to application create, read, update, and
delete (CRUD) operations:
HTTP method CRUD Action

GET Read returns requested data

POST Create creates a new record

PUT Update updates an existing record

DELETE Delete deletes an existing record


– Examples: a GET request to /user/ returns a list of
registered users
– a POST request to /user/123 creates a user with the
ID 123 using the body data
– a PUT request to /user/123 updates user 123 with the 
body data
– a GET request to /user/123 returns the details of user 123
– a DELETE request to /user/123 deletes user 123
• HTTP headers. Information such as authentication
tokens/cookies can be contained in the HTTP request
header.
• Body Data. Data is normally transmitted in the HTTP
body in an identical way to HTML <form> submissions or
by sending a single JSON-encoded data string.
• The Response : The response payload can be whatever is practical: data,
HTML, an image, an audio file, and so on. Data responses are typically JSON-
encoded (but can be CSV, XML). You could allow the return format to be
specified in the request — for example, /user/123?format=json
• An appropriate HTTP status code should also be set in the response
header. 200 OK is most often used for successful requests, although 201
Created may also be returned when a record is created. Errors should return
an appropriate code such as 400 Bad Request, 404 Not Found, 401
Unauthorized, and so on.
• However, there are no strict rules. Endpoint URLs, HTTP methods, body data,
and response types can be implemented as you like. For example, POST, PUT
are often used interchangeably so any will create or update a record.
• POST and GET are two common HTTP Request used for building REST API’s.
GET request are meant to fetch data from specified resource and POST are
meant to submit data to a specified resource.
• Post method facilitates you to send large amount of data because data is
send in the body. Post method is secure because data is not visible in URL bar
but it is not used as popularly as GET method. On the other hand GET
method is more efficient and used more than POST.
• 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) {  
   // --  
})  
The following table specifies some of the properties associated with request object.

Index Properties Description

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
• 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
• Once you :
• res.send() or res.redirect() or res.render(),
• you cannot do it again, otherwise, there will be uncaught error.
• Response redirect method
• res.redirect()
• Redirect the requesting user agent to the given absolute or relative URL.
• return res.redirect(url);
• Or: return res.redirect(statusCode, url);
• return res.redirect('http://google.com');
Argument Type Details

1 statusCode Number? An optional status code (e.g. 301). (If omitted, a status code of 302 will be assumed.)

A URL expression (see below for complete specification).


2 url String
e.g. "http://google.com" or "/login"
• The domain-relative redirect. For example, if you
were on http://example.com/admin/post/new,
the following redirect to /checkout would land
you at http://example.com/checkout:
• return res.redirect('/checkout');
• Pathname-relative redirects. If you were on 
http://example.com/admin/post/new, the
following redirect would land you at
http//example.com/admin/post:
• return res.redirect('..');
• Response Send method
• This method is used to send HTTP response.
• Examples:
• res.send({ crocodiles: ['judy', 'nigel', 'spence'] }) //
will convert to a string with JSON.stringify
res.send('<p>Nice to Eat Ya!</p>') res.send('  
• .....some html  
• ');  
•  res.status(406).send('Not Acceptable');  
•  res.status(404).send('Not Found');  
• Response Render method
• 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) 
{  
•   // ...  
• });  
• Response JSON method :
• This method returns the response in JSON
format.
• Example:
• res.json(null)  
• res.json({ name: 'ajeet' })
• res.end()
• We can use res.end() if we want to end the
response without providing any data. This could be useful for a
404 page, for example:
• res.status(404).end();
• In the code above we are explicitly setting the HTTP status
code and immediately after that ending the response.
• But what if we want to send some data and end the response?
The answer is simple, res.send() (and remember, res.json())
both allow us to send some data and they also end the
response, so there's no need to explicitly call res.end()
• Response Cookie method
• 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 });  
•  
• Response ClearCookie method
• As the name specifies, the clearCookie method is used to clear the cookie
specified by name.
• res.clearCookie('name', { path: '/admin' });  
• What are routes?
• Routes are ways that we can handle user navigation to various URLs throughout
our application. A route specifies how an application responds to a client
request to a particular route, URI or path and a specific HTTP request method
(GET, POST, etc.). It can handle different types of HTTP requests.
•  
• For example, if we wanted to greet a user with a Hello, World! message on the
home page, we may do something like this:
• const express = require('express')
• const app = express()
• app.get('/', function (req, res) {
• res.send('Hello, World!')
• })
•  
• app.get('/api/users', function(req, res) {
• var user_id = req.param('id');
• var token = req.param('token');
• var geo = req.param('geo');
• });
• #ROUTE PARAMETERS
• The route parameters are used to capture the values that are specified to a
particular position in the URL. They are called the URL segments.
• The values obtained are made available in a req.params object, using the name of
the route parameter specified in the path as the keys of the values.
• Route parameter is significant in functionality like edit, update, and delete. We
generally pass the ID on the parameter and extract it from the request. The syntax
is like this.
• http://localhost:3000/api/user/:id
• Now, at Express Router, we can access the ID using the following code.
• http://localhost:3000/api/user/1
• In the req.params, the following will be available: { “id”: “1” }
• So, we can access the 1 using the following code.
• req.params.id
• one more example:
• // http://localhost:8080/api/1
• app.get('/api/:version', function(req, res) {
• res.send(req.params.version);
• });
• POST query parameters are sent by HTTP clients for example by forms, or when
performing a POST request sending data.
• How can you access this data?
•  
• If the data was sent as  JSON, using Content-Type: application/json, you will use
the express.json() middleware:
• const express = require('express')
• const app = express()
• app.use(express.json())
•  
• If the data was sent using Content-Type: application/x-www-form-urlencoded, you
will use the express.urlencoded() middleware :
• const express = require('express')
• const app = express()
• app.use(express.urlencoded())
• In both cases you can access the data by referencing it from Request.body:
• app.post('/form', (req, res) => {
• const name = req.body.name
• })
• What is middleware?
• Middleware is any number of functions that are invoked by the
Express.js routing layer before your final request handler is, and
thus sits in the middle between a raw request and the final
intended route. It basically lets you configure how your express
application works.
•  
• Basic Idea: A web server can be seen as a function that takes in a
request and outputs a response. Middlewares are functions
executed in the middle after the incoming request then produces
an output which could be the final output passed or could be
used by the next middleware until the cycle is completed,
meaning we can have more than one middleware and they will
execute in the order they are declared. middleware A below will
execute before middleware B, middleware Bbefore middleware
C.We can pass variable from one middleware to another.
• Middleware Usage:
• To set up a middleware, you can invoke app.use() for every middleware
layer that you want to add. Middleware can be generic to all paths, or
triggered only on specific path(s) your server handles. Below is an
example of middleware declaration.
• var app = express();
• app.use(function () {}) //added to all paths or globally
• app.get('/someroute', function() {}) //added to a specific path
•  
• You should install the following important modules along with express

• body-parser − This is a node.js middleware for handling JSON, Raw,
Text and URL encoded form data.
• cookie-parser − Parse Cookie header and populate req.cookies with an
object keyed by the cookie names.
• multer − This is a node.js middleware for handling multipart/form-
data.
• Middleware : chaining a bunch of functions
• Let's start by creating the world's simplest Express server:
• import express from "express";
•  
• const app = express();
• app.get('/hello', (req, res) => {
• res.send('world'));
• }
• It creates a route /hello that responds a body world.
• Now let's change the last line just a little bit by adding a 3rd param
called next:
• app.get('/hello', (req, res, next) => {
• res.send('world'));
• next();
• }
• We have created an Express Middleware.
• Middleware == Function with next()
• A middleware is just a function with three params (req, res, next), where next is a function that allows
you to chain multiple functions. Let's see another example:
• // returns true if server time is in AM
• function isMorning() {...}
•  
• app.get("/hello",
• // middleware #1
• (req, res, next) => {
• if (isMorning()) {
• res.send("morning");
• } else {
• next();
• }
• },
• // middleware #2: called when isMorning() === false
• (req, res, next) => {
• res.send("afternoon");
• }
• );
• Here we are chaining two middleware functions to handle /hello route. We use next() to pass control
from the first middleware to the second.
• In real-world scenarios, middlewares are useful for sharing common code among routes.
•  
• Express Sessions
• How to use sessions to identify users across requests
• By default Express requests are sequential and no request can be linked
to each other. There is no way to know if this request comes from a
client that already performed a request previously.
• Users cannot be identified unless using some kind of mechanism that
makes it possible.
• That’s what sessions are.
• When implemented, every user of your API or website will be assigned a
unique session, and this allows you to store the user state.
• We’ll use the express-session module, which is maintained by the
Express team.
• You can install it using
• npm install express-session
• and once you’re done, you can instantiate it in your application with
• const session = require('express-session')
• This is a middleware, so you install it in Express
using
• const express = require('express')
• const session = require('express-session')
•  
• const app = express()
• app.use(session({
• 'secret': '343ji43j4n3jn4jk3n'
• }))
• After this is done, all the requests to the app
routes are now using sessions.
• secret is the only required parameter, but there
are many more you can use. It should be a
randomly unique string for your application.
• The session is attached to the request, so you
can access it using req.session here:
• app.get('/', (req, res, next) => {
• // req.session
• }
• This object can be used to get data out of the session, and also
to set data:
• req.session.name = 'Flavio'
• console.log(req.session.name) // 'Flavio'
• This data is serialized as JSON when stored, so you are safe to
use nested objects.
• You can use sessions to communicate data to middleware that’s
executed later, or to retrieve it later on, on subsequent
requests.
• Where is the session data stored? It depends on how you set up
the express-session module.
• It can store session data in
• memory, not meant for production
• a database like MySQL or Mongo
• a memory cache like Redis or Memcached
• There is a big list of 3rd packages that implement a wide variety of different
compatible caching stores in https://github.com/expressjs/session
• All solutions store the session id in a cookie, and keep the data server-side.
The client will receive the session id in a cookie, and will send it along with
every HTTP request.
• We’ll reference that server-side to associate the session id with the data
stored locally.
• Memory is the default, it requires no special setup on your part, it’s the
simplest thing but it’s meant only for development purposes.
• The best choice is a memory cache like Redis, for which you need to setup
its own infrastructure.
• Another popular package to manage sessions in Express is cookie-session,
which has a big difference: it stores data client-side in the cookie. I do not
recommend doing that because storing data in cookies means that it’s
stored client-side, and sent back and forth in every single request made by
the user. It’s also limited in size, as it can only store 4 kilobytes of data.
Cookies also need to be secured, but by default they are not, since secure
Cookies are possible on HTTPS sites and you need to configure them if you
have proxies.
How to handle cookies in Express JS?

Cookies are very useful to store small piece of web application data and cookies are
stored on the user’s computer by the user’s web browser while the user is browsing.
Express uses the same methods, Cookies, as most other web frameworks to track
sessions. A cookie will have the session ID so that Express can look it up on each
request.
Express came up with cookie-parser middleware to handle Cookies, by using this
module you can easily manage your express application Cookies.
Let’s install cookie-parser middleware through npm, issue below mentioned command
from your terminal and project root folder where your package.json file resides.
npm install cookie-parser --save
lets use this middleware along with all the other middleware. Remember that the
middleware is processed in order, so add it before other middleware so other
middleware can use it.
const express = require('express');
const cookieParser = require('cookie-parser');
 
const app = express();
// add cookieParser to middleware stack
app.use(cookieParser());
 
// for signing the cookies.
//app.use(express.cookieParser('my secret
here'));
The Cookie parser gives us access to req.cookies with an
object keyed by the Cookie names. Optionally you may
enable signed cookie support by passing a secret string,
which assigns req.secret so it may be used by other
middleware. you can access singed Cookies
with req.signedCookies.
How to set Cookie
The res.cookie() function is used for setting Cookie

app.get('/cookie',function(req, res){
    res.cookie(cookie_name , 'cookie_value');
    return res.send('cookie has been set!');
});
• You can also set additional options of Cookies by passing an object
as 3rd argument to the above function. let set maximum age of a
Cookie.
•app.get('/cookie',function(req, res){
•    let minute = 60 * 1000;
•    res.cookie(cookie_name, 'cookie_value', { maxAge: minute });
•    return res.send('cookie has been set!');
•});
• You can tell Express to set your Cookie only over HttpOnly.This flag
will tell browsers to not allow client side script access to the Cookie.
• res.cookie(cookie_name , 'cookie_value', { HttpOnly: true});
• You can tell express to use https encrypted
channel to exchange cookie data with secure flag.
• res.cookie(cookie_name , 'cookie_value',
{ secure: true});
• You can all so set Cookie expire time in
milliseconds.
• res.cookie(cookie_name , 'cookie_value',
{expire : 24 * 60 * 60 * 1000 }); // 24 hours
• Reading Cookies?
• You can access your Cookies via request
object, req.cookies.cookie_name or req.cooki
es, second one return all the app cookies
where first one return only the specific cookie.
If the request contains no Cookies, it defaults
to {}.
Deleting cookie?
You can also easily deleted Cookies by using response
object’s clearCookie function, which accepts the name of the
Cookie which you want to delete. You can also delete your
Cookies from browser developers tools.
•app.get('/clearcookie', function(req,res){
•     res.clearCookie('cookie_name');
•     res.send('Cookie deleted');
•});

You might also like