Експрес, обяснен с примери - Инсталиране, маршрутизиране, Middleware и др

Експрес

Когато става въпрос за изграждане на уеб приложения с помощта на Node.js, създаването на сървър може да отнеме много време. През годините Node.js е узрял достатъчно благодарение на подкрепата от общността. Използването на Node.js като бекенд за уеб приложения и уебсайтове помага на разработчиците да започнат да работят бързо върху тяхното приложение или продукт.

В този урок ще разгледаме Express, който е рамка на Node.js за уеб разработка, която се предлага с функции като маршрутизиране и изобразяване и поддръжка на REST API.

Какво е Express?

Express е най-популярната рамка на Node.js, тъй като изисква минимална настройка за стартиране на приложение или API и е бърза и едновременно неинфонирана. С други думи, той не налага собствената си философия, че приложение или API трябва да бъдат изградени по специфичен начин, за разлика от Rails и Django. Неговата гъвкавост може да се изчисли чрез броя на npmналичните модули, което го прави едновременно включен. Ако имате основни познания по HTML, CSS и JavaScript и как работи Node.js като цяло, за нула време ще можете да започнете с Express.

Express е разработен от TJ Holowaychuk и сега се поддържа от Node.js Foundation и разработчици с отворен код. За да започнете с разработката с помощта на Express, трябва да имате инсталирани Node.js и npm. Можете да инсталирате Node.js на вашата локална машина и заедно с него идва помощната програма на командния ред, npmкоято ще ни помогне да инсталираме плъгини или така наречените зависимости по-късно в нашия проект.

За да проверите дали всичко е инсталирано правилно, моля, отворете терминала си и напишете:

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

Ако получавате номера на версията вместо грешка, това означава, че сте инсталирали Node.js и npm успешно.

Защо да използвам Express?

Преди да започнем с механизма за използване на Express като бекенд рамка, нека първо разгледаме защо трябва да го обмислим да използваме или причините за популярността му.

  • Express ви позволява да създавате едностранични, многостранични и хибридни уеб и мобилни приложения. Друга често срещана употреба е да се осигури API за клиент (независимо дали е уеб или мобилен).
  • Той се предлага с механизъм за шаблони по подразбиране, Jade, който помага да се улесни потокът от данни в структурата на уебсайта и поддържа други механизми за шаблони.
  • Той поддържа MVC (Model-View-Controller), много често срещана архитектура за проектиране на уеб приложения.
  • Той е междуплатформен и не се ограничава до която и да е конкретна операционна система.
  • Той използва Node.js еднонишко и асинхронен модел.

Всеки път, когато създаваме проект с помощта npm, нашият проект трябва да има package.jsonфайл.

Създаване на package.json

JSON (JavaScript Object Notation) файл съдържа всяка информация за всеки Express проект. Броят на инсталираните модули, името на проекта, версията и друга мета информация. За да добавим Express като модул в нашия проект, първо трябва да създадем директория на проекта и след това да създадем файл package.json.

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

Това ще генерира package.jsonфайл в корена на директорията на проекта. За да инсталираме който и да е модул npm, трябва да има package.jsonфайл в тази директория.

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

Инсталиране на Express

Сега имаме package.jsonфайл, можем да инсталираме Express, като изпълним командата:

npm install --save express

Можем да потвърдим, че Express е инсталирал правилно по два начина. Първо, във package.jsonфайла с име, dependenciesв който съществува нашата Express , ще има нова секция :

{ "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" } }

Вторият начин е, че нова папка, наречена node_modulesвнезапно, се появи в корена на директорията на нашия проект. Тази папка съхранява пакетите, които инсталираме локално в нашия проект.

Изграждане на сървър с Express

За да използваме нашия инсталиран пакет за Express framework и да създадем просто сървърно приложение, ние ще създадем файла index.js, в основата на директорията на нашия проект.

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!'));

За да стартирате сървъра, отидете на вашия терминал и напишете:

node index.js

Това ще стартира сървъра. Това минимално приложение ще слуша на порт 3000. Ние отправяме заявка чрез нашия браузър //localhost:3000и сървърът ни ще отговори, Hello Worldна който браузърът е клиент и съобщението ще се покаже там.

Първият ред на нашия код използва requireфункцията за включване на expressмодула. Ето как включваме и използваме пакет, инсталиран от npm, във всеки JavaScript файл в нашия проект. Преди да започнем да използваме Express, трябва да дефинираме негов екземпляр, който обработва заявката и отговора от сървъра към клиента. В нашия случай това е променливата app.

app.get()е функция, която казва на сървъра какво да прави, когато getсе извика заявка по дадения маршрут. Той има функция за обратно извикване, (req, res)която прослушва входящия reqобект на заявка и отговаря съответно с помощта на resобект за отговор. И двете, reqи resса достъпни за нас от Express рамката.

В reqобекта представлява искането за HTTP и има имоти за низ заявка заявка, параметри, тялото и HTTP заглавки. Обектът res представлява HTTP отговора, който Express приложение изпраща, когато получи HTTP заявка. В нашия случай изпращаме текст Hello Worldвсеки път, когато е направена заявка за маршрута /.

И накрая, app.listen()е функцията, която стартира порт и хост, в нашия случай localhostвръзките за прослушване на входящи заявки от клиент. Можем да определим номера на порта като 3000.

Анатомия на експресно приложение

Типична структура на файл на сървър на Express най-вероятно ще съдържа следните части:

Зависимости

Импортиране на зависимости като самия експрес. Тези зависимости се инсталират като се използва npmв предишния пример.

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

This is pattern is commonly known as MVC, model-view-controller. Simply because our database model, the UI of the application and the controllers (in our case, routes) are written and stored in separate files. This design pattern that makes any web application easy to scale if you want to introduce more routes or static files in the future and the code is maintainable.