0% found this document useful (0 votes)
6 views51 pages

Exsp Js

This document provides an overview of back-end server applications using Express.js, covering topics such as the importance of back-end frameworks, creating an Express.js server, building web APIs, and using middleware functions. It includes practical examples and explanations of how to manage routes, endpoints, and dependencies in Express.js applications. The content is structured to guide users through the process of developing full-stack web applications with Express.js.

Uploaded by

amani sayari
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)
6 views51 pages

Exsp Js

This document provides an overview of back-end server applications using Express.js, covering topics such as the importance of back-end frameworks, creating an Express.js server, building web APIs, and using middleware functions. It includes practical examples and explanations of how to manage routes, endpoints, and dependencies in Express.js applications. The content is structured to guide users through the process of developing full-stack web applications with Express.js.

Uploaded by

amani sayari
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/ 51

INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.

js 1/36

Web Technologies 1
Back-end server applications with Express.js

Maxime Guériau & Alexandre Pauchet

INSA Rouen - Département ASI


BO.B.RC.18, [email protected]
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 2/36

Plan

1 Back-end frameworks

2 Your first Express.js server

3 Building web APIs with ExpressJS

4 Express middleware functions

5 Managing routes and endpoints in Express


INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 3/36

Full stack web development


Spoil (TW2) and today’s plan

Front end Back end

HTTP Request

SQL query
HTTP Response
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 3/36

Full stack web development


Spoil (TW2) and today’s plan

Front end Back end

HTTP Request

SQL query
HTTP Response
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 4/36

Back-end frameworks
Why using a framework?

Problem: NodeJS server APIs are actually pretty low-level:


you build/read the request manually
you write/build the response manually
you need a lot of (boring) processing code

Solution: Choose and use an existing framework!


INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 5/36

Back-end frameworks
Which one?

Source: [1]
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 6/36

Your first Express.js server


NodeJS vs. ExpressJS (rappel)
NodeJSMini/server.js (adapted from [2]) ExpressJSMini/server.js (from [3])
1 // import http module; documentation: https:// 1 // import express module and create your
nodejs.org/api/http.html express app
2 const http = require(’http’); 2 const express = require(’express’);
3 3 const app = express();
4 // set the server port 4
5 const port = 3000; 5 // set the server host and port
6 6 const port = 3000;
7 // create a http server endpoint 7
8 const server = http.createServer((req, res) => 8 // create your express server endpoint
{ 9 app.get(’/’, function (req, res) {
9 // set the response of your endpoint 10 // set the response of your endpoint
10 res.end(’Hello World!’); 11 res.send(’Hello World!’);
11 }); 12 });
12 13
13 // run the server 14 // run the server
14 server.listen(port, () => { 15 app.listen(port, () => {
15 // callback executed when the server is 16 // callback executed when the server is
launched launched
16 console.log(‘Server running on port ${port17 console.log(‘Express app listening on port
}‘); ${port}‘);
17 }); 18 });
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 7/36

Your first Express.js server


Installation (rappel)

Remarque
Express is not part of the NodeJS APIs
⇒We need to install Express via npm!

To install Express, simply run:


npm install express

and then run your (express app) server:


node server.js

output:

Express app listening on port 3000


INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 8/36

Your first Express.js server


ExpressJS
Hello world example [4]

require()
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 8/36

Your first Express.js server


ExpressJS
Hello world example [4]

listen()
listen()
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 8/36

Your first Express.js server


ExpressJS
Hello world example [4]

app. ( )
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 8/36

Your first Express.js server


Handler
Hello world example [4] parameters

Request Response
req
res
res.send()
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 9/36

Building web APIs with ExpressJS


Recall:
API endpoints [4] Web services
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 9/36

Building web APIs with ExpressJS


API endpoints [4]

Server-side web API [5]


”A server-side web Application Programming Interface is a
programmatic interface consisting of one or more publicly exposed
endpoints to a defined request–response message system, typically
expressed in JSON or XML, which is exposed via the web—most
commonly by means of an HTTP-based web server.”

API endpoint [6]


”An API endpoint is the point of entry in a communication channel
when two systems are interacting. It refers to touchpoints of the
communication between an API and a server. The endpoint can be
viewed as the means from which the API can access the resources
they need from a server to perform their task. An API endpoint is
basically a fancy word for a URL of a server or service.”
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 9/36

Building web APIs with ExpressJS


Recall:
API endpoints [4] File servers
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 10/36

Building web APIs with ExpressJS


ServingSolution
static files [4] 2: Statically served files
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 11/36

Building web APIs with ExpressJS


Example: ExpressJSstatic

/ExpressJSstatic
/node modules ExpressJSstatic/server.js ...
package.json 5 // enable your express app to serve static files located in
/public ”public” directory
6 app.use(express.static(’public’));
index.html
resource.txt ...
server.js
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 12/36

Building web APIs with ExpressJS


Uploading
Managing server
dependencies (rappel) [4] code

node_modules
node_modules
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 12/36

Building web APIs with ExpressJS


Managing
Managing dependencies
dependencies (rappel) [4]

node_modules

npm

npm package.json
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 12/36

Building web APIs with ExpressJS


package.json
Managing dependencies (rappel) [4]

package.json

package.json
$ npm init

package.json
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 13/36

Building web APIs with ExpressJS


Managing dependencies (rappel)

Example of an auto-generated package.json:


{
"name": "expressjsstatic",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "Alexandre Pauchet",
"license": "ISC",
"dependencies": {
"express": "ˆ4.18.1"
}
}
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 14/36

Building web APIs with ExpressJS


Saving
Managing deps
dependencies to[4]package.json
(rappel)

$ npm install --save express


$ npm install --save body-parser
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 14/36

Building web APIs with ExpressJS


Saving
Managing deps
dependencies to[4]package.json
(rappel)

$ rm -rf node_modules

$ npm install
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 14/36

Building web APIs with ExpressJS


npm
Managing scripts
dependencies (rappel) [4]

$ npm

$ npm start
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 15/36

Building web APIs with ExpressJS


Managing dependencies (rappel): fixing nodemon

An other example of dependency is nodemon module, that you can


install as a local development dependency:
npm install --save-dev nodemon

Doing so will add a few specific lines in your package.json:


...
"devDependencies": {
"nodemon": "ˆ2.0.20"
},
...

You can not use nodemon directly as a command line but you can
update your package.json so npm can now use nodemon:
...
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon server.js"
},
...
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 16/36

Express middleware functions


Definitions [7]

Express
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
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.
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 17/36

Express middleware functions


Definitions [7]

Middleware functions can


perform the following tasks:
Execute any code;
Make changes to the request
and the response objects;
Call the next middleware
function in the stack (using
next());
End the request-response
cycle.
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 18/36

Express middleware functions


Definitions [7]

An Express application can use the following types of middleware:


1 Application-level middleware
2 Error-handling middleware
3 Built-in middleware
4 Third-party middleware
5 Router-level middleware
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 19/36

Express middleware functions


Application-level middleware [7]

You can bind application-level middleware to an instance of the app


object by using:
app.use() for any type of HTTP request;
app.<method>() for a specific type of HTTP request:
app.get()
app.post()
app.put()
app.delete()
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 20/36

Express middleware functions


Application-level middleware [8]

HTTP method for which the middleware function applies.

Path (route) for which the middleware function applies.

The middleware function.

Callback argument to the middleware function, called next by


convention.
HTTP response argument to the middleware function, called
res by convention.
HTTP request argument to the middleware function,
called req by convention.
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 21/36

Express middleware functions


Application-level middleware: ExpressJSMiddlewareUse/server.js

...
8 // endpoint executed for all requests
9 app.use(function (req, res, next) {
10 console.log(req.url);
11 // there is no response sent, we mush call next()
12 next();
13 });
14
15 // endpoint with a specific route
16 app.use(’/home’, function (req, res) {
17 res.send(’Welcome home!’);
18 // we sent a response, no need to call next()
19 });
20
21 // endpoint with a general route
22 app.use(’/’, function (req, res) {
23 res.send(’Hello World!’);
24 // we sent a response, no need to call next()
25 });
...
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 22/36

Express middleware functions


Application-level middleware: ExpressJSMiddlewareMethod/server.js

...
5 // enable your express app to serve static files located in ”public” directory
6 app.use(express.static(’public’));
7 // enable your express app to read request body (for POST requests)
8 app.use(express.urlencoded({ extended: true }));
...
13 // endpoint executed for all requests
14 app.use(function (req, res, next) {
15 console.log(req.url);
16 console.log(req.method);
17 console.log(req.query); // shows GET params
18 console.log(req.body); // show POST params
19 next();
20 });
...
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 22/36

Express middleware functions


Application-level middleware: ExpressJSMiddlewareMethod/server.js

...
22 // endpoint with a specific route
23 app.get(’/data’, function (req, res) {
24 res.send(’GET /data’);
25 });
26
27 // endpoint with a specific route
28 app.post(’/data’, function (req, res) {
29 res.send(’POST /data’);
30 });
...
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 23/36

Express middleware functions


Error-handling middleware [7]

You can 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), for
instance:
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send(’Something broke!’)
})

Note: In addition to handling the error, it is a good practice to inform


the user of the type or error, by sending the corresponding standard
HTTP Status Code [9] in your HTTP response.
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 24/36

Express middleware functions


Error-handling example: ExpressJSMiddlewareErrors/server.js, adapted from [10]

...
5 //import the fs module
6 const fs = require(’fs’);
...
11 app.get(’/’, (req, res, next) => {
12 fs.readFile(’./file.txt’, { encoding: ’utf8’ }, (err, data) => {
13 if (err) {
14 next(err);
15 } else {
16 res.send(’’+ data);
17 }
18 })
19 })
20
21 app.use((err, req, res, next) => {
22 console.error(err.stack);
23 res.status(500).send(’Something broke!’);
24 })
...
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 25/36

Express middleware functions


Built-in middleware [7]

Express has many built-in middleware functions, for instance:


express.static: serves static assets such as HTML files,
images, etc.
express.json: parses incoming requests with JSON payloads.
express.urlencoded: parses incoming requests with
URL-encoded payloads.
and more1 .

1
See the full list of built-in middleware functions available in express:
https://github.com/senchalabs/connect#middleware
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 26/36

Express middleware functions


Built-in middleware [7] example: ExpressJSstatic

/ExpressJSstatic
/node modules ExpressJSstatic/server.js ...
package.json 5 // enable your express app to serve static files located in
/public ”public” directory
6 app.use(express.static(’public’));
index.html
resource.txt ...
server.js

Note: you have already seen this one!


INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 27/36

Express middleware functions


Built-in middleware [7]

You can also use third-party middleware to add functionality to your


Express app:
1 Install the Node.js module for the required functionality (using
npm)
2 Load it in your app at the application level or at the router level
(using require())

For instance :
npm install sqlite3

and then in your code:


const sqlite3 = require(’
sqlite3’);
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 28/36

Express middleware functions

An Express application can use the following types of middleware:


1 Application-level middleware
2 Error-handling middleware
3 Built-in middleware
4 Third-party middleware
5 Router-level middleware
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 29/36

Routing
Routes vs. endpoints

Routing [11]
”Routing refers to determining how an application responds to a
client request to a particular endpoint, which is a URI (or path)
and a specific HTTP request method (GET, POST, and so on).”

Routing in defining middleware functions corresponding to


Express = each endpoint of your API.

Endpoint in
Request method + Route path
Express =
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 30/36

Routing
How to route

Routing in Express basically refers to associating a middleware


function per API endpoint using:
app.method(path,handler)
where:
(route) path: is the route path (URL or the resource requested) of
the endpoint
(route) handler: is the middleware function callback fired
everytime there is a new request

Important: your callback function must use the (req, res,


next) parameters and explicitly call next() if your endpoint is not
sending a final response!
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 31/36

Routing
Route paths [13]

Express route paths can be:


strings,
string patterns,
regular expressions.

Not an expert with regular expressions? Use the online


Express Route Tester [12].
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 31/36

Routing
Route paths [13]

Examples of route paths based on strings2 :


Route path Target URL
’/’ root route /
’/home’ /home
’/file.txt’ /file.txt

2
Again, you can test your route paths using Express Route Tester [12]
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 31/36

Routing
Route paths [13]

Examples of route paths based on string patterns2 :


Route path Target URL
’/ab?cd’ /abd and /abcd
’/ab+cd’ /abcd, /abbcd, /abbbcd, etc.
’/ab*cd’ /abcd, /abxcd, /abRANDOMcd, /ab123cd, etc.
’/ab(cd)?e’ /abe and /abcde

2
Again, you can test your route paths using Express Route Tester [12]
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 32/36

Routing
Route parameters

Route parameters are named URL segments that are used to


capture the values specified at their position in the URL. The name of
route parameters must be made up of “word characters”
([A-Za-z0-9 ]). Hyphen (-) and dot (.) characters are interpreted
literally

Examples of route paths using route parameters3 :


Route path Target URL
’/user/:user/movie/:movie’ /user/bob/movie/findingne
etc.
/years/:from-:to /years/1998-2022, etc.

3
Again, you can test your route paths using Express Route Tester [12]
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 33/36

Routing
Response methods

You can send a response to the client and terminate the


request-response cycle by using a response method on the
response object res:
Method Target URL
res.download() Prompt a file to be downloaded.
res.end() End the response process.
res.json() Send a JSON response.
res.redirect() Redirect a request.
res.send() Send a response of various types.
res.sendFile() Send a file as an octet stream.
res.sendStatus() Set the response status code and send its string
representation as the response body.
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 34/36

Routing
And when there is no route?

Problem: How do I do if the requested


path matches no route?

Important: If no response method is


called from a route handler, the client
request will be left hanging.
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 35/36

Routing
Serving a 404 error page example: ExpressJS404/server.js

...
13 // basic root route
14 app.get(’/’, function(req, res){
15 res.send(’Hello world!’);
16 });
17
18 // the 404 route (always keep this as the last route)
19 app.get(’*’, function(req, res){
20 res.status(404);
21 //serve a static html file (can be done using express.static)
22 res.sendFile(”404.html”, {root: ”.”});
23 });
...
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 36/36

Conclusion

Key takeaways:
✓ ExpressJS is a powerful (and popular) back-end framework ...
✓ .. built on top of NodeJS, that helps at building complete web
APIs.
✓ In ExpressJS, you define middleware (callback) functions ...
✓ ... for each endpoint of your API.
✓ Routing enables your Express app to handle at the same time ...
✓ ... the requested URL and the request method.
✓ Using NodeJS modules in your Express app enables you to ...
✓ ... decompose your code, routing and middleware in separate files
...
✓ ... in order to create modular and reusable applications.
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 36/36

References and further reading/watching I


[1] Most popular backend frameworks 2012-2022. URL
https://statisticsanddata.org/data/
most-popular-backend-frameworks-2012-2022/.
[2] Go full-stack with node.js, express, and mongodb. URL
https://openclassrooms.com/fr/courses/
5614116-go-full-stack-with-node-js-express-and-mo
[3] Expressjs starter, . URL https:
//expressjs.com/en/starter/hello-world.html.
[4] Victoria Kirst. CS193X Web Programming Fundamentals, 2017.
URL https://web.stanford.edu/class/archive/cs/
cs193x/cs193x.1176/.
[5] Web api wikipedia. URL
https://en.wikipedia.org/wiki/Web_API.
[6] Endpoint – what is an api endpoint? URL https:
//rapidapi.com/blog/api-glossary/endpoint/.
INSA - ASI TW1 – Back-end server applications with Express.js : Back-end server applications with Express.js 36/36

References and further reading/watching II

[7] Expressjs middleware, . URL https:


//expressjs.com/en/guide/using-middleware.html.
[8] Writing expressjs middleware, . URL https://expressjs.
com/en/guide/writing-middleware.html.
[9] Http status codes. URL https:
//www.restapitutorial.com/httpstatuscodes.html.
[10] Express error handling, . URL https:
//expressjs.com/en/guide/error-handling.html.
[11] Express basic routing, . URL https:
//expressjs.com/en/starter/basic-routing.html.
[12] Express route tester, . URL http://forbeslindesay.
github.io/express-route-tester/.
[13] Express routing, . URL
https://expressjs.com/en/guide/routing.html.

You might also like