0% found this document useful (0 votes)
35 views13 pages

Chap 6 Expressintro

The document provides an introduction and overview of Express, a popular Node.js web application framework. It describes what Express is, its key features like routing, middleware and templating. It also discusses advantages of using Express and some common use cases.

Uploaded by

Pranay Bhatkar
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)
35 views13 pages

Chap 6 Expressintro

The document provides an introduction and overview of Express, a popular Node.js web application framework. It describes what Express is, its key features like routing, middleware and templating. It also discusses advantages of using Express and some common use cases.

Uploaded by

Pranay Bhatkar
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/ 13

Introduction to Express

✔ Express is a minimal and flexible Node.js web application framework


that provides a robust set of features for web and mobile applications.
✔ It is an open source framework developed and maintained by the
Node.js foundation.

✔ Express provides a minimal interface to build our applications. It


provides us the tools that are required to build our app. It is flexible as
there are numerous modules available on npm, which can be directly
plugged into Express.

✔ Express was developed by TJ Holowaychuk and is maintained by


the Node.js foundation and numerous open source contributors.

✔ Express is a node js web application framework that provides broad


features for building web and mobile applications. It is used to build a
single page, multipage, and hybrid web application.

✔ It's a layer built on the top of the Node js that helps manage servers and
routes

Why Express JS?

● Express was created to make APIs and web applications with ease,

● It saves a lot of coding time almost by half and still makes web and

● mobile applications are efficient.

● Another reason for using express is that it is written in javascript


as javascript is an easy language even if you don't have a previous
knowledge of any language. Express lets so many new developers
enter the field of web development.
The reason behind creating an express framework for node js is:

● Time-efficient
● Fast

● Economical

● Easy to learn

● Asynchronous

Features of Express JS

● Fast Server-Side Development

The features of node js help express saving a lot of time.

● Middleware

Middleware is a request handler that has access to the application's request-


response cycle.

● Routing

It refers to how an application's endpoint's URLs respond to client requests.

● Templating

It provides templating engines to build dynamic content on the web pages


by creating HTML templates on the server.

● Debugging

Express makes it easier as it identifies the exact part where bugs are
Advantages of Using Express With Node.js

● Express is Unopinionated, and we can customize it.

● For request handling, we can use Middleware.

● A single language is used for frontend and backend development.

● Express is fast to link it with databases like MySQL, MongoDB, etc.

● Express allows dynamic rendering of HTML Pages based on passing


arguments to templates.

Limitations of Express JS

● Sometimes, there is no structural way to organize things, and the


code becomes non-understandable.

● There are so many issues with callbacks.

● The error messages that will come are challenging to understand.

Companies That Are Using Express JS

● Netflix

● IBM

● ebay

● Uber
.

Also Read: Node.js for Beginners: How to Get Started

Installation and the First Program

To install Express JS on your system first you need to install node js then we will
write a command to install express in the terminal.

● npm install express

The express js will be installed in your system.

Now let’s write our first basic program in which we will print “Welcome To
Simplilearn” on the server.

our first app using Express.


Create a new file called index.js and type the following in it.

var express = require('express');


var app = express();

app.get('/', function(req, res){


res.send("Hello world!");
});
app.listen(3000);

How the App Works?


The first line imports Express in our file, we have access to it through the
variable Express. We use it to create an application and assign it to var
app.
app.get(route, callback)
This function tells what to do when a get request at the given route is
called. The callback function has 2
parameters, request(req) and response(res). The
request object(req) represents the HTTP request and has properties for
the request query string, parameters, body, HTTP headers, etc.
Similarly, the response object represents the HTTP response that the
Express app sends when it receives an HTTP request.
res.send()
This function takes an object as input and it sends this to the requesting
client. Here we are sending the string "Hello World!".
app.listen(port, [host], [backlog], [callback]])
S.No Argument & Description
.

1 port
A port number on which the server should accept incoming
requests.

2 host
Name of the domain. You need to set it when you deploy your apps
to the cloud.

3 backlog
The maximum number of queued pending connections. The default
is 511.

4 callback
An asynchronous function that is called when the server starts
listening for requests.

ExpressJS - Routing
Web frameworks provide resources such as HTML pages, scripts,
images, etc. at different routes.
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.
We can also have multiple different methods at the same route. For
example,
var express = require('express');
var app = express();

app.get('/hello', function(req, res){


res.send("Hello World!");
});

app.post('/hello', function(req, res){


res.send("You just called the post method at '/hello'!\n");
});

app.listen(3000);
Routers
Defining routes like above is very tedious to maintain. To separate the
routes from our main index.js file, we will use Express.Router. Create a
new file called things.js and type the following in it.
var express = require('express');
var router = express.Router();

router.get('/', function(req, res){


res.send('GET route on things.');
});
router.post('/', function(req, res){
res.send('POST route on things.');
});

//export this router to use in our index.js


module.exports = router;
Now to use this router in our index.js, type in the following before
the app.listen function call.
var express = require('Express');
var app = express();

var things = require('./things.js');

//both index.js and things.js should be in same directory


app.use('/things', things);
app.listen(3000);
The app.use function call on route '/things' attaches the things router
with this route. Now whatever requests our app gets at the '/things', will
be handled by our things.js router. The '/' route in things.js is actually a
subroute of '/things'. Visit localhost:3000/things/ and you will see the
following output.
Routers are very helpful in separating concerns and keep relevant
portions of our code together. They help in building maintainable code.
You should define your routes relating to an entity in a single file and
include it using the above method in your index.js file.
ExpressJS - HTTP Methods
The HTTP method is supplied in the request and specifies the operation
that the client has requested. The following table lists the most used
HTTP methods −

S.No Method & Description


.

1 GET
The GET method requests a representation of the specified
resource. Requests using GET should only retrieve data and should
have no other effect.

2 POST
The POST method requests that the server accept the data
enclosed in the request as a new object/entity of the resource
identified by the URI.

3 PUT
The PUT method requests that the server accept the data enclosed
in the request as a modification to existing object identified by the
URI. If it does not exist then the PUT method should create one.

4 DELETE
The DELETE method requests that the server delete the specified
resource
ExpressJS - URL Building
We can now define routes, but those are static or fixed. To use the
dynamic routes, we SHOULD provide different types of routes. Using
dynamic routes allows us to pass parameters and process based on
them.
Here is an example of a dynamic route −
var express = require('express');
var express = require('express');
var app = express();

app.get('/:id', function(req, res){


res.send('The id you specified is ' + req.params.id);
});
app.listen(3000);

var express = require('express');


var app = express();

app.get('/things/:name/:id', function(req, res) {


res.send('id: ' + req.params.id + ' and name: ' + req.params.name);
});
app.listen(3000);
To test the above code, go
to http://localhost:3000/things/tutorialspoint/12345.

you can use the req.params object to access all the parameters you
pass in the url. Note that the above 2 are different paths. They will never
overlap. Also if you want to execute code when you get '/things' then
you need to define it separately.

Express.js express.Router() Function


The express.Router() function is used to create a new router object. This
function is used when you want to create a new router object in your program
to handle requests.
Example 1: Filename: index.js
var express = require('express');
var app = express();
var PORT = 3000;

// Single routing
var router = express.Router();

router.get('/', function (req, res, next) {


console.log("Router Working");
res.end();
})

app.use(router);

app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
Example 2: Filename: index.js
var express = require('express');
var app = express();
var PORT = 3000;

// Multiple routing
var router1 = express.Router();
var router2 = express.Router();
var router3 = express.Router();

router1.get('/user', function (req, res, next) {


console.log("User Router Working");
res.end();
});

router2.get('/admin', function (req, res, next) {


console.log("Admin Router Working");
res.end();
});
router2.get('/student', function (req, res, next) {
console.log("Student Router Working");
res.end();
});
app.use(router1);
app.use(router2);
app.use(router3);
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});

Express.js req.params Property


The req.params property is an object containing properties mapped to the
named route “parameters”. For example, if you have the route /student/:id,
then the “id” property is available as req.params.id. This object defaults to {}.
Syntax:
req.params
Example 1: Filename: index.js
var express = require('express');
var app = express();
var PORT = 3000;

app.get('/:id', function (req, res) {


console.log(req.params['id']);
res.send();
});

app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
Example 2: Filename: index.js
var express = require('express');
const e = require('express');
var app = express();
var PORT = 3000;

var student = express.Router();


app.use('/student', student);

student.get('/profile/:start/:end', function (req, res) {


console.log("Starting Page: ", req.params['start']);
console.log("Ending Page: ", req.params['end']);
res.send();
})

app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});

Output:
Now open your browser and make GET request
to http://localhost:3000/student/profile/12/17, now you can see the
following output on your console:
Server listening on PORT 3000
Starting Page: 12
Ending Page: 17

You might also like