express 路由中间件_Express通过示例进行解释-安装,路由,中间件等

express 路由中间件

表达 (Express)

When it comes to build web applications using Node.js, creating a server can take a lot of time. Over the years Node.js has matured enough due to the support from community. Using Node.js as a backend for web applications and websites help the developers to start working on their application or product quickly.

在使用Node.js构建Web应用程序时,创建服务器可能需要很多时间。 多年来,由于社区的支持,Node.js已经足够成熟。 使用Node.js作为Web应用程序和网站的后端可以帮助开发人员快速开始开发其应用程序或产品。

In this tutorial, we are going to look into Express which is a Node.js framework for web development that comes with features like routing and rendering and support for REST APIs.

在本教程中,我们将研究Express,这是一个用于Web开发的Node.js框架,具有路由和渲染等功能以及对REST API的支持。

什么是快递? (What is Express?)

Express is the most popular Node.js framework because it requires minimum setup to start an application or an API and is fast, and unopinionated at the same time. In other words, it does not enforces its own philosophy that a application or API should be built in a specific way, unlike Rails and Django. Its flexibility can be calculated by the number of npm modules available which makes it pluggable at the same time. If you have basic knowledge of HTML, CSS, and JavaScript and how Node.js works in general, in no time you will be able to get started with Express.

Express是最流行的Node.js框架,因为它需要最少的设置来启动应用程序或API,并且速度快且同时不受限制。 换句话说,与Rails和Django不同,它没有实施自己的哲学,即应以特定方式构建应用程序或API。 它的灵活性可以通过可用的npm模块数量来计算,这使得它可以同时插入。 如果您具有HTML,CSS和JavaScript的基本知识以及Node.js的一般工作原理,那么您很快就可以开始使用Express。

Express was developed by TJ Holowaychuk and is now maintained by Node.js foundation and open source developers. To get started with the development using Express, you need to have Node.js and npm installed. You can install Node.js on your local machine and along with it comes the command line utility npm that will help us to install plugins or as called dependencies later on in our project.

Express由TJ Holowaychuk开发,现在由Node.js基金会和开源开发人员维护。 要开始使用Express进行开发,您需要安装Node.js和npm。 您可以在本地计算机上安装Node.js ,并附带命令行实用程序npm ,它将帮助我们稍后在项目中安装插件或称为依赖项。

To check if everything is installed correctly, please open your terminal and type:

要检查所有内容是否正确安装,请打开终端并输入:

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

If you are getting the version number instead of an error that means you have installed Node.js and npm successfully.

如果获取的是版本号而不是错误,则表示您已成功安装Node.js和npm。

为什么要使用Express? (Why use Express?)

Before we start with mechanism of using Express as the backend framework, let us first explore why we should consider it using or the reasons of its popularity.

在开始使用Express作为后端框架的机制之前,让我们首先探讨为什么应该考虑使用Express或其流行的原因。

  • Express lets you build single page, multi-page, and hybrid web and mobile applications. Other common backend use is to provide an API for a client (whether web or mobile).

    Express使您可以构建单页,多页以及混合的Web和移动应用程序。 后端的其他常见用法是为客户端(无论是Web还是移动设备)提供API。
  • It comes with a default template engine, Jade which helps to facilitate the flow of data into a website structure and does support other template engines.

    它带有一个默认的模板引擎Jade,它有助于促进数据流到网站结构中,并且确实支持其他模板引擎。
  • It supports MVC (Model-View-Controller), a very common architecture to design web applications.

    它支持MVC(模型-视图-控制器),这是设计Web应用程序的非常常见的体系结构。
  • It is cross-platform and is not limited to any particular operating system.

    它是跨平台的,不限于任何特定的操作系统。
  • It leverages upon Node.js single threaded and asynchronous model.

    它利用Node.js单线程和异步模型。

Whenever we create a project using npm, our project must have a package.json file.

每当我们使用npm创建项目时,我们的项目都必须具有package.json文件。

创建package.json (Creating package.json)

A JSON (JavaScript Object Notation) file is contains every information about any Express project. The number of modules installed, the name of the project, the version, and other meta information. To add Express as a module in our project, first we need to create a project directory and then create a package.json file.

JSON(JavaScript对象表示法)文件包含有关任何Express项目的所有信息。 安装的模块数量,项目名称,版本和其他元信息。 要将Express作为模块添加到我们的项目中,首先我们需要创建一个项目目录,然后创建一个package.json文件。

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

This will generate a package.json file in the root of the project directory. To install any module from npm we need to have package.json file exist in that directory.

这将在项目目录的根目录中生成一个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 (Installing Express)

Now we have package.json file, we can install Express by running the command:

现在我们有了package.json文件,我们可以通过运行以下命令来安装Express:

npm install --save express

We can confirm that Express has correctly installed by two ways. First, there will be new section in package.json file named dependencies under which our Express exists:

我们可以通过两种方式确认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"
  }
}

Second way is that a new folder called node_modules suddenly appeared in the root of our project directory. This folder stores the packages we install locally in our project.

第二种方法是在我们的项目目录的根目录中突然出现一个名为node_modules的新文件夹。 此文件夹存储我们在项目中本地安装的软件包。

使用Express构建服务器 (Building a Server with Express)

To use our installed package for Express framework and create a simple server application, we will create the file, index.js, at the root of our project’s directory.

要将安装的软件包用于Express框架并创建一个简单的服务器应用程序,我们将在项目目录的根目录下创建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!'));

To start the server, go to your terminal and type:

要启动服务器,请转到终端并输入:

node index.js

This will start the server. This bare-minimum application will listen on port 3000. We make a request through our browser on http://localhost:3000 and our server will respond with Hello World to which the browser is the client and the message will be shown there.

这将启动服务器。 这个最简单的应用程序将在端口3000上进行侦听。我们通过位于http://localhost:3000上的浏览器发出请求,并且服务器将以浏览器为客户端的Hello World进行响应,并在此处显示消息。

The first line of our code is using the require function to include the express module. This is how we include and use a package installed from npm in any JavaScript file in our project. Before we start using Express, we need to define an instance of it which handles the request and response from the server to the client. In our case, it is the variable app.

我们代码的第一行使用require函数来包含express模块。 这就是我们在项目中的任何JavaScript文件中包含和使用从npm安装的软件包的方式。 在开始使用Express之前,我们需要定义一个实例来处理从服务器到客户端的请求和响应。 在我们的例子中,它是变量app

app.get() is a function that tells the server what to do when a get request at the given route is called. It has a callback function (req, res) that listen to the incoming request req object and respond accordingly using res response object. Both req and res are made available to us by the Express framework.

app.get()是一个函数,它告诉服务器在给定路由处调用get请求时该怎么做。 它具有一个回调函数(req, res) ,该函数侦听传入的请求req对象,并使用res响应对象相应地进行响应。 Express框架向我们提供了reqres

The req object represents the HTTP request and has properties for the request query string, parameters, body, and HTTP headers. The res object represents the HTTP response that an Express app sends when it gets an HTTP request. In our case, we are sending a text Hello World whenever a request is made to the route /.

req对象代表HTTP请求,并具有请求查询字符串,参数,正文和HTTP标头的属性。 res对象表示Express应用在收到HTTP请求时发送的HTTP响应。 在本例中,每当对路径/发出请求时,我们都会发送文本Hello World

Lastly, app.listen() is the function that starts a port and host, in our case the localhost for the connections to listen to incoming requests from a client. We can define the port number such as 3000.

最后, app.listen()是启动端口和主机的函数,在本例中为连接的localhost主机,以侦听来自客户端的传入请求。 我们可以定义端口号,例如3000

快速应用程序剖析 (Anatomy of an Express Application)

A typical structure of an Express server file will most likely contain the following parts:

Express服务器文件的典型结构很可能包含以下部分:

Dependencies

依存关系

Importing the dependencies such as the express itself. These dependencies are installed using npm like we did in the previous example.

导入依赖项,例如快递本身。 这些依赖关系是使用npm来安装的,就像在上一个示例中一样。

Instantiations

实例化

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

这些是创建对象的语句。 要使用express,我们必须从中实例化app变量。

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.

在Express服务器中执行的最后一个命令是启动我们服务器的app.listen()函数。

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.

路由是指服务器端应用程序如何响应特定端点的客户端请求。 该端点由URI(例如//books类的路径)和HTTP方法(例如GET,POST,PUT,DELETE等)组成。

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:

路由可以是良好的旧网页或REST API端点。 在这两种情况下,路由的相似语法可以定义为:

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.

路由器有助于分离诸如不同端点之类的问题,并将源代码的相关部分保持在一起。 它们有助于构建可维护的代码。 所有路由都在app.listen()函数调用之前定义。 在典型的Express应用程序中, app.listen()将是最后执行的函数。

路由方式 (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.

HTTP是客户端和服务器之间进行通信的标准协议。 它为客户端提出请求提供了不同的方法。 每个路由至少都具有hanlder函数或回调。 该回调函数确定来自服务器的特定路由响应。 例如, app.get()的路由用于处理GET请求,并作为响应发送简单消息。

// 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.

将上面的代码视为具有两个端点/home/about 。 如果客户请求首页,则只会用Home Page响应,并且在/about上会发送响应: About Page 。 如果选择了两个定义的路由中的任何一个,我们将使用res.send函数将字符串发送回客户端。

路由参数 (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.

路由参数被命名为URL段,用于捕获URL中在其位置处指定的值。 在这种情况下,使用req.params对象是因为它可以访问url中传递的所有参数。

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

The request URL from client in above source code will be http://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.

上面源代码中来自客户端的请求URL将为http://localhost:3000/books/23 。 路径参数的名称必须由字符([A-Za-z0-9_])组成。 在我们的应用程序中,路由参数的一个非常普遍的用例是拥有404路由。

// 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: http://localhost:3000/abcd. In response, we will get the 404 message.

如果现在使用node index.js从命令行启动服务器,然后尝试访问URL: http://localhost:3000/abcd 。 作为响应,我们将收到404消息。

中间件功能 (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.

中间件功能是可以访问请求对象( req ),响应对象( res )和应用程序的请求-响应周期中的next功能的那些功能。 这些功能的目的是为诸如解析请求正文,添加响应头,对请求-响应周期进行其他更改,结束请求-响应周期并调用下一个中间件功能之类的任务修改请求和响应对象。

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.

next功能是Express路由器中的功能,用于执行当前中间件之后的其他中间件功能。 如果中间件函数确实包括next() ,则意味着请求-响应周期在那里结束。 函数next()的名称完全是任意的,您可以随意命名,但是遵循最佳实践并遵循一些约定很重要,特别是在与其他开发人员合作时。

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.

同样,在编写自定义中间件时,请不要忘记向其添加next()函数。 如果不提及next()则请求-响应周期将挂在虚无处,并且您的servr可能会导致客户端超时。

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.

要设置任何中间件,无论是自定义的还是作为npm模块可用,我们都使用app.use()函数。 它作为一个可选参数路径和一个强制参数回调。 在我们的情况下,我们没有使用可选的参数路​​径。

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.

这次,当客户端请求端点/home时,您只会看到类似的提示,因为在app.use()提到了路由。 当客户端请求端点/about时,终端中将不会显示任何/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.

中间件功能的顺序很重要,因为它们定义了何时调用哪个中间件功能。 在上面的示例中,如果我们在中间件app.use('/home')...之前定义路由app.get('/home')... app.use('/home')... ,则不会调用中间件功能。

第三方中间件功能 (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.

中间件功能是一种有用的模式,它允许开发人员在其应用程序内重用代码,甚至以NPM模块的形式与他人共享代码。 中间件的基本定义是具有三个参数的函数:请求(或req),响应(res)和下一个,我们在上一节中进行了观察。

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.

通常,在基于Express的服务器应用程序中,我们将使用第三方中间件功能。 这些功能由Express本身提供。 它们就像可以使用npm安装的插件,这就是Express灵活的原因。

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

Express应用程序中最常用的中间件功能包括:

bodyParser (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:

它允许开发人员处理传入的数据,例如主体有效载荷。 有效负载只是我们从客户端接收到的要处理的数据。 对POST方法最有用。 它使用以下方法安装:

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.

它可能是任何Express应用程序中最常用的第三方中间件功能之一。

cookieParser (cookieParser)

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

它解析Cookie头,并用由cookie名称作为键的对象填充req.cookies 。 要安装它,

$ 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.

common是可以在应用程序中使用的预定义格式情况。 还有其他预定义格式,例如tiny和dev,但是您也可以使用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.

为了提供诸如CSS样式表,图像等静态文件,Express提供了内置的中间件功能express.static 。 静态文件是客户端从服务器下载的那些文件。

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.

它是Express框架随附的唯一中间件功能,我们可以在应用程序中直接使用它。 所有其他中间件都是第三方。

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:

默认情况下,Express不允许提供静态文件。 我们必须使用此中间件功能。 Web应用程序开发中的常见做法是将所有静态文件存储在项目根目录的“ public”目录下。 通过编写index.js文件,我们可以为该文件夹提供静态文件,包括:

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

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

现在,我们公共目录中的静态文件将被加载。

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

多个静态目录 (Multiple Static Directories)

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

要使用多个静态资产目录,请多次调用express.static中间件函数:

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.

修复路径前缀也可以作为express.static中间件功能的第一个参数提供。 由于实际路径在项目中不存在,因此称为虚拟路径前缀

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

If we now try to load the files:

如果现在尝试加载文件:

http://localhost:3000/static/css/style.css
http://localhost:3000/static/images/logo.png
http://localhost:3000/static/images/bg.png
http://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.

模板引擎是允许我们使用不同模板语言的库。 模板语言是一组特殊的指令(语法和控制结构),它们指示引擎如何处理数据。 通过Express,可以轻松使用模板引擎。 流行的模板引擎(例如Pug,EJS,Swig和Handlebars)与Express兼容。 但是,Express带有默认模板引擎Jade,它是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.

为了演示如何使用模板引擎,我们将使用Pug。 它是一个功能强大的模板引擎,提供诸如过滤器,包含,插值等功能。要使用它,我们首先必须使用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.

该命令将安装哈巴狗,并验证是否已正确安装,只需查看package.json文件即可。 要首先将其与我们的应用程序一起使用,我们必须将其设置为模板引擎,并创建一个新目录'./views',我们将在其中存储与模板引擎相关的所有文件。

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.

由于我们使用的app.set()表示服务器文件中的配置,因此在定义任何路由或中间件功能之前,必须先将它们放置。

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

views ,创建名为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 http://localhost:3000/hello you will see the output Hello World rendered correctly.

由于我们已经将Pug设置为模板引擎,因此在res.render我们不必提供.pug扩展名。 此函数将任何.pug文件中的代码呈现为HTML,以供客户端显示。 浏览器只能呈现HTML文件。 如果现在启动服务器,并访问路由http://localhost:3000/hello您将看到正确呈现的输出Hello World

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:

在Pug中,您必须注意,我们不必像在HTML中那样向元素编写结束标记。 上面的代码将呈现为HTML:



   
      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.

与原始HTML文件相比,使用模板引擎的优势在于它们为通过数据执行任务提供了支持。 HTML无法直接呈现数据。 诸如Angular和React之类的框架与模板引擎共享此行为。

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:

对于上述情况,我们的index.pug文件将写为:

doctype html
  html
    head
      title= title
    body
      h1= message

The output will be the same as previous case.

输出将与以前的情况相同。

Express App的项目结构 (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.

由于Express对使用它的开发人员的要求并不高,因此有时它可能会使您应该遵循的项目结构有些不知所措。 它没有正式定义的结构,但是任何基于Node.js的应用程序遵循的最常见用例是在不同模块中分离不同任务。 这意味着要有单独JavaScript文件。

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

让我们看一下基于Express的Web应用程序的典型结构。

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.

这种模式通常称为MVC,即模型视图控制器。 仅仅是因为我们的数据库模型,应用程序的UI和控制器(在我们的情况下是路由)被编写并存储在单独的文件中。 如果您将来想引入更多路由或静态文件并且代码是可维护的,则这种设计模式使任何Web应用程序都易于扩展。

翻译自: https://www.freecodecamp.org/news/express-explained-with-examples-installation-routing-middleware-and-more/

express 路由中间件

你可能感兴趣的:(中间件,vue,python,java,javascript)