Professional Documents
Culture Documents
Express
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
2. req.baseurl It specifies the URL path on which a router instance was mounted.
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.
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.
1 statusCode Number? An optional status code (e.g. 301). (If omitted, a status code of 302 will be assumed.)
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');
•});