0% found this document useful (0 votes)
14 views30 pages

5.2-Unit 5 - ExpressApp

The document outlines the steps to build an Express API for handling CRUD operations on 'bears' with a standard URL structure and RESTful HTTP verbs. It covers setting up the server, defining routes, using middleware, and testing the API with Postman. Additionally, it discusses the use of built-in, third-party, and error-handling middleware, as well as implementing a template engine for rendering HTML.

Uploaded by

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

5.2-Unit 5 - ExpressApp

The document outlines the steps to build an Express API for handling CRUD operations on 'bears' with a standard URL structure and RESTful HTTP verbs. It covers setting up the server, defining routes, using middleware, and testing the API with Postman. Additionally, it discusses the use of built-in, third-party, and error-handling middleware, as well as implementing a template engine for rendering HTML.

Uploaded by

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

Express App Using JSON

Express Application
• We are going to build an API that will:
• Handle CRUD for an item (we're going to use bears)
• Have a standard URL (http://example.com/api/bears and http://example.com/api/bears/:bear_id)
• Use the proper HTTP verbs to make it RESTful (GET, POST, PUT, and DELETE)
• Return JSON data
• Log all requests to the console

2
Getting Started
• We will need to define our Node packages, start our server using
Express, define our model, declare our routes using Express, and last but not
least, test our API.
• Here is our file structure.

3
Node Packages package.json
• As with all of our Node projects, we will define the packages we need
in package.json.
• Go ahead and create that file with these packages.

4
Setting up Server
• Node will look here when starting the application so that it will know how we want
to configure our application and API.

5
Setting up Server
• Base Setup: In our base setup, we pull in all the packages we pulled in using npm.
• We'll grab express, define our app, get bodyParser and configure our app to use it.
• We can also set the port for our application.

6
Setting up Server
• Routes for Our API This section will hold all of our routes.
• The structure for using the Express Router let's us pull in an instance of the router.
• We can then define routes and then apply those routes to a root URL (in this
case, API).

7
Setting up Server
• Start our Server
• We'll have our express app listen to the port we defined earlier.
• Then our application will be live and we can test it!

8
Starting the server
• Let's make sure that everything is working up to this point.
• We will start our Node app and then send a request to the one route we defined to
make sure we get a response.
• Let's start our server.
• From the command line, type:

9
Starting the server
• You should see your Node app start up and Express will create a server.

10
Testing API using Postman
• Postman will help us test our API.
• It will basically send HTTP requests to a URL of our choosing.
• We can even pass in parameters (which we will soon) and authentication (which
we won't need for this tutorial).
• Open up Postman and let's walk through how to use it.

11
Testing API using Postman
• Enter http://localhost:8080/api into the URL.
• GET is what we want since we just want to get data.
• Now click Send.

12
Using Middleware
• Express is a routing and middleware web framework that has minimal functionality
of its own: An Express application is essentially a series of middleware function
calls.
• 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.
• The next middleware function is commonly denoted by a variable named next.

13
Using Middleware
• Middleware functions can perform the following tasks:
• Execute any code.
• Make changes to the request and the response objects.
• End the request-response cycle.
• Call the next middleware function in the stack.
• If the current middleware function does not end the request-response cycle, it must
call next() to pass control to the next middleware function.
• Otherwise, the request will be left hanging.

14
Types of Middleware
• An Express application can use the following types of middleware:
• Application-level middleware
• Router-level middleware
• Error-handling middleware
• Built-in middleware
• Third-party middleware
• You can load application-level and router-level middleware with an optional mount
path.
• You can also load a series of middleware functions together, which creates a sub-
stack of the middleware system at a mount point.

15
Application-level middleware
• Bind application-level middleware to an instance of the app object by using
the app.use() and app.METHOD() functions, where METHOD is the HTTP method
of the request that the middleware function handles (such as GET, PUT, or POST)
in lowercase.
• This example shows a middleware function with no mount path.
• The function is executed every time the app receives a request.

16
Application-level middleware
• This example shows a middleware function mounted on the /user/:id path.
• The function is executed for any type of HTTP request on the /user/:id path.

• This example shows a route and its handler function (middleware system).
• The function handles GET requests to the /user/:id path.

17
Application-level middleware
• Here is an example of loading a series of middleware functions at a mount point,
with a mount path.
• It illustrates a middleware sub-stack that prints request info for any type of HTTP
request to the /user/:id path.

18
Application-level middleware
• Route handlers enable you to define multiple routes for a path.
• The example below defines two routes for GET requests to the /user/:id path.
• The second route will not cause any problems, but it will never get called because
the first route ends the request-response cycle.

19
Router-level middleware
• Router-level middleware works in the same way as application-level middleware,
except it is bound to an instance of express.Router().

• Load router-level middleware by using the router.use() and router.METHOD()


functions.
• The next example code replicates the middleware system that is shown above for
application-level middleware, by using router-level middleware:

20
Router-level middleware

21
Router-level middleware
• To skip the rest of the router’s middleware functions, call next('router') to pass
control back out of the router instance.

22
Error-handling middleware
• Error-handling middleware always takes four arguments. You must provide four
arguments to identify it as an error-handling middleware function. Even if you don’t
need to use the next object, you must specify it to maintain the signature.
Otherwise, the next object will be interpreted as regular middleware and will fail to
handle errors.
• Define error-handling middleware functions in the same way as other middleware
functions, except with four arguments instead of three, specifically with the
signature (err, req, res, next)):

23
Built-in middleware
• The middleware functions that were previously included with Express are now in
separate modules; see the list of middleware functions.
• Express has the following built-in middleware functions:
• express.static serves static assets such as HTML files, images, and so on.
• express.json parses incoming requests with JSON payloads.
• express.urlencoded parses incoming requests with URL-encoded payloads.

24
Third-party middleware
• Use third-party middleware to add functionality to Express apps.
• Install the Node.js module for the required functionality, then load it in your app at
the application level or at the router level.
• The following example illustrates installing and loading the cookie-parsing
middleware function cookie-parser.

25
Using Template Engine
• A template engine enables you to use static template files in your application.
• At runtime, the template engine replaces variables in a template file with actual
values, and transforms the template into an HTML file sent to the client.
• This approach makes it easier to design an HTML page.

26
Using Template Engine
• To render template files, set the following application setting properties, set
in app.js in the default app created by the generator: views, the directory where the
template files are located. Eg: app.set('views', './views').
• This defaults to the views directory in the application root directory.view engine, the
template engine to use. For example, to use the Pug template engine:
app.set('view engine', 'pug').

27
Using Template Engine
• Then install the corresponding template engine npm package; for example to install
Pug:

• After the view engine is set, you don’t have to specify the engine or load the
template engine module in your app; Express loads the module internally, as
shown below (for the above example).

28
Using Template Engine
• Create a Pug template file named index.pug in the views directory, with the
following content:

• Then create a route to render the index.pug file. If the view engine property is not
set, you must specify the extension of the view file. Otherwise, you can omit it.

• When you make a request to the home page, the index.pug file will be rendered as
HTML.

29
Thank You

30

You might also like