Ekspres forklaret med eksempler - Installation, routing, Middleware og mere

Express

Når det kommer til at opbygge webapplikationer ved hjælp af Node.js, kan det tage meget tid at oprette en server. Gennem årene har Node.js modnet nok på grund af support fra samfundet. Brug af Node.js som en backend til webapplikationer og websteder hjælper udviklerne med at begynde at arbejde på deres applikation eller produkt hurtigt.

I denne vejledning skal vi undersøge Express, som er en Node.js-ramme til webudvikling, der kommer med funktioner som routing og gengivelse og support til REST API'er.

Hvad er Express?

Express er den mest populære Node.js-ramme, fordi det kræver minimal opsætning for at starte en applikation eller en API og er hurtig og uopineret på samme tid. Med andre ord håndhæver det ikke sin egen filosofi, at en applikation eller API skal bygges på en bestemt måde i modsætning til Rails og Django. Dens fleksibilitet kan beregnes ud fra antallet af npmtilgængelige moduler, hvilket gør det tilsluttet på samme tid. Hvis du har grundlæggende viden om HTML, CSS og JavaScript, og hvordan Node.js fungerer generelt, er du på ingen tid i stand til at komme i gang med Express.

Express blev udviklet af TJ Holowaychuk og vedligeholdes nu af Node.js foundation og open source-udviklere. For at komme i gang med udviklingen ved hjælp af Express skal du have Node.js og npm installeret. Du kan installere Node.js på din lokale maskine, og sammen med det kommer kommandolinjeprogrammet, npmder hjælper os med at installere plugins eller som kaldes afhængigheder senere i vores projekt.

For at kontrollere, om alt er installeret korrekt, skal du åbne din terminal og skrive:

node --version v5.0.0 npm --version 3.5.2

Hvis du får versionsnummeret i stedet for en fejl, betyder det, at du har installeret Node.js og npm med succes.

Hvorfor bruge Express?

Før vi begynder med mekanismen til at bruge Express som backend-ramme, lad os først undersøge, hvorfor vi bør overveje at bruge det eller grundene til dets popularitet.

  • Express giver dig mulighed for at oprette enkeltsider, flersides og hybrid web- og mobilapplikationer. Anden almindelig backend-brug er at levere en API til en klient (hvad enten det er web eller mobil).
  • Den leveres med en standardskabelonmotor, Jade, som hjælper med at lette datastrømmen til en webstedsstruktur og understøtter andre skabelonmotorer.
  • Det understøtter MVC (Model-View-Controller), en meget almindelig arkitektur til design af webapplikationer.
  • Det er på tværs af platforme og er ikke begrænset til et bestemt operativsystem.
  • Det udnytter Node.js enkelt gevind og asynkron model.

Hver gang vi opretter et projekt ved hjælp af npm, skal vores projekt have en package.jsonfil.

Oprettelse af package.json

En JSON-fil (JavaScript Object Notation) indeholder alle oplysninger om ethvert Express-projekt. Antallet af installerede moduler, projektets navn, versionen og anden metainformation. For at tilføje Express som et modul i vores projekt skal vi først oprette en projektmappe og derefter oprette en package.json-fil.

mkdir express-app-example cd express-app-example npm init --yes

Dette genererer en package.jsonfil i roden til projektmappen. For at installere ethvert modul fra skal npmvi have en package.jsonfil i den mappe.

{ "name": "express-web-app", "version": "0.1.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "license": "MIT" }

Installation af Express

Nu har vi en package.jsonfil, vi kan installere Express ved at køre kommandoen:

npm install --save express

Vi kan bekræfte, at Express er korrekt installeret på to måder. For det første vil der være et nyt afsnit i package.jsonfilen med navnet, dependencieshvor vores Express findes:

{ "name": "express-web-app", "version": "0.1.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "license": "MIT", "dependencies": { "express": "4.16.0" } }

Den anden måde er, at en ny mappe kaldet node_modulespludselig dukkede op i roden til vores projektmappe. Denne mappe gemmer de pakker, vi installerer lokalt i vores projekt.

Opbygning af en server med Express

For at bruge vores installerede pakke til Express framework og oprette en simpel serverapplikation opretter vi filen index.js, i roden af ​​vores projekts katalog.

const express = require('express'); const app = express(); app.get('/', (req, res) => res.send('Hello World!')); app.listen(3000, () => console.log('Example app listening on port 3000!'));

For at starte serveren skal du gå til din terminal og skrive:

node index.js

Dette starter serveren. Denne applikation med minimumsniveau vil lytte på port 3000. Vi fremsætter en anmodning via vores browser på, //localhost:3000og vores server vil svare, Hello Worldsom browseren er klienten med, og meddelelsen vises der.

Den første linje i vores kode bruger requirefunktionen til at inkludere expressmodulet. Sådan inkluderer og bruger vi en pakke installeret fra npm i enhver JavaScript-fil i vores projekt. Før vi begynder at bruge Express, skal vi definere en forekomst af den, der håndterer anmodningen og svaret fra serveren til klienten. I vores tilfælde er det variablen app.

app.get()er en funktion, der fortæller serveren, hvad de skal gøre, når getder ringes til en anmodning på den givne rute. Den har en tilbagekaldsfunktion, (req, res)der lytter til det indgående anmodningsobjekt reqog svarer i overensstemmelse hermed ved hjælp af ressvarobjektet. Begge reqog resstilles til rådighed for os af Express-rammen.

Den reqobjekt repræsenterer HTTP-forespørgslen og har egenskaber til forespørgselsanmodningen streng, parametre, krop og HTTP headers. Res-objektet repræsenterer HTTP-svaret, som en Express-app sender, når den får en HTTP-anmodning. I vores tilfælde sender vi en tekst, Hello Worldnår der fremsættes en anmodning til ruten /.

Endelig app.listen()er den funktion, der starter en port og vært, i vores tilfælde localhostfor forbindelserne at lytte til indgående anmodninger fra en klient. Vi kan definere portnummeret som f.eks 3000.

Anatomi af en ekspress applikation

En typisk struktur for en Express-serverfil vil sandsynligvis indeholde følgende dele:

Afhængigheder

Import af afhængigheder som selve udtrykket. Disse afhængigheder installeres ved hjælp af, npmsom vi gjorde i det foregående eksempel.

Instantiations

These are the statements to create an object. To use express, we have to instantiate the app variable from it.

Configurations

These statements are the custom application based settings that are defined after the instantiations or defined in a separate file (more on this when discuss the project structure) and required in our main server file.

Middleware

These functions determine the flow of request-response cycle. They are executred after every incoming request. We can also define custom middleware functions. We have section on them below.

Routes

They are the endpoints defined in our server that helps to perform operations for a particular client request.

Bootstrapping Server

The last that gets executed in an Express server is the app.listen() function which starts our server.

We will now start disussing sections that we haven’t previously discussed about.

Routing

Routing refers to how an server side application responds to a client request to a particular endpoint. This endpoint consists of a URI (a path such as / or /books) and an HTTP method such as GET, POST, PUT, DELETE, etc.

Routes can be either good old web pages or REST API endpoints. In both cases the syntax is similar syntax for a route can be defined as:

app.METHOD(PATH, HANDLER);

Routers are helpful in separating concerns such as different endpoints and keep relevant portions of the source code together. They help in building maintainable code. All routes are defined before the function call of app.listen(). In a typical Express application, app.listen() will be last function to execute.

Routing Methods

HTTP is a standard protocol for a client and a server to communicate over. It provides different methods for a client to make request. Each route has at least on hanlder function or a callback. This callback function determines what will be the response from server for that particular route. For example, a route of app.get() is used to handle GET requests and in return send simple message as a response.

// GET method route app.get('/', (req, res) => res.send('Hello World!'));

Routing Paths

A routing path is a combination of a request method to define the endpoints at which requests can be made by a client. Route paths can be strings, string patterns, or regular expressions.

Let us define two more endpoints in our server based application.

app.get('/home', (req, res) => { res.send('Home Page'); }); app.get('/about', (req, res) => { res.send('About'); });

Consider the above code as a bare minimum website which has two endpoints, /home and /about. If a client makes a request for home page, it will only response with Home Page and on /about it will send the response: About Page. We are using the res.send function to send the string back to the client if any one of the two routes defined is selected.

Routing Parameters

Route parameters are named URL segments that are used to capture the values specified at their position in the URL. req.params object is used in this case because it has access to all the parameters passed in the url.

app.get('/books/:bookId', (req, res) => { res.send(req.params); });

The request URL from client in above source code will be //localhost:3000/books/23. The name of route parameters must be made up of characters ([A-Za-z0-9_]). A very general use case of a routing parameter in our application is to have 404 route.

// For invalid routes app.get('*', (req, res) => { res.send('404! This is an invalid URL.'); });

If we now start the server from command line using node index.js and try visiting the URL: //localhost:3000/abcd. In response, we will get the 404 message.

Middleware Functions

Middleware functions are those functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The objective of these functions is to modify request and response objects for tasks like parsing request bodies, adding response headers, make other changes to request-response cycle, end the request-response cycle and call the next middleware function.

The next function is a function in the Express router which is used to execute the other middleware functions succeeding the current middleware. If a middleware function does include next() that means the request-response cycle is ended there. The name of the function next() here is totally arbitary and you can name it whatever you like but is important to stick to best practices and try to follow a few conventions, especially if you are working with other developers.

Also, when writing a custom middleware do not forget to add next() function to it. If you do not mention next() the request-response cycle will hang in middle of nowhere and you servr might cause the client to time out.

Let use create a custom middleware function to grasp the understanding of this concept. Take this code for example:

const express = require('express'); const app = express(); // Simple request time logger app.use((req, res, next) => { console.log("A new request received at " + Date.now()); // This function call tells that more processing is // required for the current request and is in the next middleware function/route handler. next(); }); app.get('/home', (req, res) => { res.send('Home Page'); }); app.get('/about', (req, res) => { res.send('About Page'); }); app.listen(3000, () => console.log('Example app listening on port 3000!'));

To setup any middleware, whether a custom or available as an npm module, we use app.use() function. It as one optional parameter path and one mandatory parameter callback. In our case, we are not using the optional paramaeter path.

app.use((req, res, next) => { console.log('A new request received at ' + Date.now()); next(); });

The above middleware function is called for every request made by the client. When running the server you will notice, for the every browser request on the endpoint /, you will be prompt with a message in your terminal:

A new request received at 1467267512545

Middleware functions can be used for a specific route. See the example below:

const express = require('express'); const app = express(); //Simple request time logger for a specific route app.use('/home', (req, res, next) => { console.log('A new request received at ' + Date.now()); next(); }); app.get('/home', (req, res) => { res.send('Home Page'); }); app.get('/about', (req, res) => { res.send('About Page'); }); app.listen(3000, () => console.log('Example app listening on port 3000!'));

This time, you will only see a similar prompt when the client request the endpoint /home since the route is mentioned in app.use(). Nothing will be shown in the terminal when the client requests endpoint /about.

Order of middleware functions is important since they define when to call which middleware function. In our above example, if we define the route app.get('/home')... before the middleware app.use('/home')..., the middleware function will not be invoked.

Third Party Middleware Functions

Middleware functions are useful pattern that allows developers to reuse code within their applications and even share it with others in the form of NPM modules. The essential definition of middleware is a function with three arguments: request (or req), response (res), and next which we observer in the previous section.

Often in our Express based server application, we will be using third party middleware functions. These functions are provided by Express itself. They are like plugins that can be installed using npm and this is why Express is flexible.

Some of the most commonly used middleware functions in an Express appication are:

bodyParser

It allows developers to process incoming data, such as body payload. The payload is just the data we are receiving from the client to be processed on. Most useful with POST methods. It is installed using:

npm install --save body-parser

Usage:

const bodyParser = require('body-parser'); // To parse URL encoded data app.use(bodyParser.urlencoded({ extended: false })); // To parse json data app.use(bodyParser.json());

It is probably one of the most used third-party middleware function in any Express applicaiton.

cookieParser

It parses Cookie header and populate req.cookies with an object keyed by cookie names. To install it,

$ npm install --save cookie-parser
const cookieParser = require('cookie-parser'); app.use(cookieParser());

session

This middleware function creates a session middleware with given options. A session is often used in applications such as login/signup.

$ npm install --save session
app.use( session({ secret: 'arbitary-string', resave: false, saveUninitialized: true, cookie: { secure: true } }) );

morgan

The morgan middleware keeps track of all the requests and other important information depending on the output format specified.

npm install --save morgan
const logger = require('morgan'); // ... Configurations app.use(logger('common'));

common is a predefined format case which you can use in the application. There are other predefined formats such as tiny and dev, but you can define you own custom format too using the string parameters that are available to us by morgan.

A list of most used middleware functions is available at this link.

Serving Static Files

To serve static files such as CSS stylesheets, images, etc. Express provides a built in middleware function express.static. Static files are those files that a client downloads from a server.

It is the only middleware function that comes with Express framework and we can use it directly in our application. All other middlewares are third party.

By default, Express does not allow to serve static files. We have to use this middleware function. A common practice in the development of a web application is to store all static files under the ‘public’ directory in the root of a project. We can serve this folder to serve static files include by writing in our index.js file:

app.use(express.static('public'));

Now, the static files in our public directory will be loaded.

//localhost:3000/css/style.css //localhost:3000/images/logo.png //localhost:3000/images/bg.png //localhost:3000/index.html

Multiple Static Directories

To use multiple static assets directories, call the express.static middleware function multiple times:

app.use(express.static('public')); app.use(express.static('files'));

Virtual Path Prefix

A fix path prefix can also be provided as the first argument to the express.static middleware function. This is known as a Virtual Path Prefix since the actual path does not exist in project.

app.use('/static', express.static('public'));

If we now try to load the files:

//localhost:3000/static/css/style.css //localhost:3000/static/images/logo.png //localhost:3000/static/images/bg.png //localhost:3000/static/index.html

This technique comes in handy when providing multiple directories to serve static files. The prefixes are used to help distinguish between the multiple directories.

Template Engines

Template engines are libraries that allow us to use different template languages. A template language is a special set of instructions (syntax and control structures) that instructs the engine how to process data. Using a template engine is easy with Express. The popular template engines such as Pug, EJS, Swig, and Handlebars are compatible with Express. However, Express comes with a default template engine, Jade, which is the first released version of Pug.

To demonstrate how to use a Template Engine, we will be using Pug. It is a powerful template engine that provide features such as filters, includes, interpolation, etc. To use it, we have to first install as a module in our project using npm.

npm install --save pug

This command will install the pug and to verify that installed correctly, just take a look at the package.json file. To use it with our application first we have to set it as the template engine and create a new directory ‘./views’ where we will store all the files related to our template engine.

app.set('view engine', 'pug'); app.set('views', './views');

Since we are using app.set() which indicates configuration within our server file, we must place them before we define any route or a middleware function.

In the views direcotry, create file called index.pug.

doctype html html head tite="Hello from Pug" body p.greetings Hello World! 

To run this page, we will add the following route to our application.

app.get('/hello', (req, res) => { res.render('index'); });

Since we have already set Pug as our template engine, in res.render we do not have to provide .pug extension. This function renders the code in any .pug file to HTML for the client to display. The browsers can only render HTML files. If you start the server now, and visit the route //localhost:3000/hello you will see the output Hello World rendered correctly.

In Pug, you must notice that we do not have to write closing tags to elements as we do in HTML. The above code will be rendered into HTML as:

   Hello from Pug   

Hello World!

The advantage of using a Template Engine over raw HTML files is that they provide support for performing tasks over data. HTML cannot render data directly. Frameworks like Angular and React share this behaviour with template engines.

You can also pass values to template engine directly from the route handler function.

app.get('/', (req, res) => { res.render('index', { title: 'Hello from Pug', message: 'Hello World!' }); });

For above case, our index.pug file will be written as:

doctype html html head title= title body h1= message

The output will be the same as previous case.

Project Structure of an Express App

Since Express does not enforces much on the developer using it, sometimes it can get a bit overwhelming to what project structure one should follow. It does not has a defined structure officially but most common use case that any Node.js based application follows is to separate different tasks in different modules. This means to have separate JavaScript files.

Let us go through a typical strucutre of an Express based web application.

project-root/ node_modules/ // This is where the packages installed are stored config/ db.js // Database connection and configuration credentials.js // Passwords/API keys for external services used by your app config.js // Environment variables models/ // For mongoose schemas books.js things.js routes/ // All routes for different entities in different files books.js things.js views/ index.pug 404.pug ... public/ // All static files images/ css/ javascript/ app.js routes.js // Require all routes in this and then require this file in app.js package.json

Dette mønster er almindeligt kendt som MVC, model-view-controller. Simpelthen fordi vores databasemodel, brugergrænsefladen til applikationen og controllerne (i vores tilfælde ruter) er skrevet og gemt i separate filer. Dette designmønster, der gør enhver webapplikation let at skalere, hvis du vil introducere flere ruter eller statiske filer i fremtiden, og koden kan vedligeholdes.