In this tutorial, we will study the Express framework. This framework is built in such a way that it acts as a minimal and flexible Node.js web application framework, providing a robust set of features for building single and multipage, and hybrid web application.
该框架的构建方式使其可以充当最小且灵活的Node.js Web应用程序框架,为构建单页和多页以及混合Web应用程序提供了一组强大的功能
In this tutorial, you will learn-
What is Express.js?
Express.js is a Node js web application server framework, which is specifically designed for building single-page, multi-page, and hybrid web applications.
It has become the standard server framework for node.js. Express is the backend part of something known as the MEAN stack.
它已成为node.js的标准服务器框架。Express是称为MEAN堆栈的后端部分。
The MEAN is a free and open-source JavaScript software stack for building dynamic web sites and web applications which has the following components;
MEAN是一个免费的开源JavaScript软件堆栈,用于构建动态网站和网络应用程序,它具有以下组件:
1) MongoDB - The standard NoSQL database
2) Express.js - The default web applications framework
3) Angular.js - The JavaScript MVC framework used for web applications
4) Node.js - Framework used for scalable server-side and networking applications.
用于可扩展服务器端和网络应用程序的框架
The Express.js framework makes it very easy to develop an application which can be used to handle multiple types of requests like the GET, PUT, and POST and DELETE requests.
Express.js框架使开发应用程序变得非常容易,该应用程序可用于处理多种类型的请求,例如GET,PUT,POST和DELETE请求
Installing and using Express
Express gets installed via the Node Package Manager. This can be done by executing the following line in the command line
npm install express
The above command requests the Node package manager to download the required express modules and install them accordingly.
Let’s use our newly installed Express framework and create a simple “Hello World” application.
Our application is going to create a simple server module which will listen on port number 3000. In our example, if a request is made through the browser on this port number, then server application will send a ‘Hello’ World’ response to the client.
// use the express module
const express = require('express');
// create an object of the express module
const app = express();
// create a callback function
app.get('/', (req, res) => {
// send 'Hello World' response
res.send('Hello World!');
});
// Make the server listen on port 3000
const server = app.listen(3000, () => {
});
Code Explanation:
-
In our first line of code, we are using the require function to include the “express module.”
-
Before we can start using the express module, we need to make an object of it.
在开始使用Express模块之前,我们需要创建一个对象
-
Here we are creating a callback function. This function will be called whenever anybody browses to the root of our web application which is http://localhost:3000 . The callback function will be used to send the string ‘Hello World’ to the web page.
在这里,我们正在创建一个回调函数。每当有人浏览到我们的Web应用程序的根目录http:// localhost:3000时,都会调用此函数。回调函数将用于将字符串“ Hello World”发送到网页
-
In the callback function, we are sending the string “Hello World” back to the client. The ‘res’ parameter is used to send content back to the web page. This ‘res’ parameter is something that is provided by the ‘request’ module to enable one to send content back to the web page.
在回调函数中,我们将字符串“ Hello World”发送回客户端。“ res”参数用于将内容发送回网页。此“ res”参数是“请求”模块提供的,用于使用户可以将内容发送回网页
-
We are then using the listen to function to make our server application listen to client requests on port no 3000. You can specify any available port over here.
然后,我们使用侦听功能使我们的服务器应用程序侦听端口号3000上的客户端请求。您可以在此处指定任何可用的端口
If the command is executed successfully, the following Output will be shown when you run your code in the browser.
Output:
From the output,
-
You can clearly see that we if browse to the URL of localhost on port 3000, you will see the string ‘Hello World’ displayed on the page.
-
Because in our code we have mentioned specifically for the server to listen on port no 3000, we are able to view the output when browsing to this URL.
从输出中您可以清楚地看到,如果浏览到端口3000上的localhost的URL,您将在页面上看到字符串“ Hello World”。
因为在我们的代码中,我们特别提到了服务器在端口3000上侦听的功能,所以我们能够在浏览到该URL时查看输出。
What are Routes?
Routing determine the way in which an application responds to a client request to a particular endpoint.
路由是确定应用程序响应客户端对特定端点的请求方式
For example, a client can make a GET, POST, PUT or DELETE http request for various URL such as the ones shown below;
http://localhost:3000/Books
http://localhost:3000/Students
In the above example,
- If a GET request is made for the first URL, then the response should ideally be a list of books.
- If the GET request is made for the second URL, then the response should ideally be a list of Students.
- So based on the URL which is accessed, a different functionality on the webserver will be invoked, and accordingly, the response will be sent to the client. This is the concept of routing.
Each route can have one or more handler functions, which are executed when the route is matched.
每个路由可以具有一个或多个处理程序函数,这些函数在匹配该路由时执行
The general syntax for a route is shown below
app.METHOD(PATH, HANDLER)
Wherein,
-
app is an instance of the express module
-
METHOD is an HTTP request method (GET, POST, PUT or DELETE)
-
PATH is a path on the server.
-
HANDLER is the function executed when the route is matched.
Let’s look at an example of how we can implement routes in the express. Our example will create 3 routes as
- A /Node route which will display the string “Tutorial on Node” if this route is accessed
- A /Angular route which will display the string “Tutorial on Angular” if this route is accessed
- A default route / which will display the string “Welcome to Guru99 Tutorials.”
Our basic code will remain the same as previous examples. The below snippet is an add-on to showcase how routing is implemented.
const express = require('express');
const app = express();
app.route('/Node').get((req, res) => {
res.send('Tutorial on Node');
});
app.route('/Angular').get((req, res) => {
res.send('Tutorial on Angular');
});
app.get('/', (req, res) => {
res.send('Welcome to Guru99 Tutorial');
});
const server = app.listen(3000, () => {
});
Code Explanation:
-
Here we are defining a route if the URL http://localhost:3000/Node is selected in the browser. To the route, we are attaching a callback function which will be called when we browse to the Node URL.
The function has 2 parameters.
- The main parameter we will be using is the ‘res’ parameter, which can be used to send information back to the client.
- The ‘req’ parameter has information about the request being made. Sometimes additional parameters could be sent as part of the request being made, and hence the ‘req’ parameter can be used to find the additional parameters being sent.
- We are using the send function to send the string “Tutorial on Node” back to the client if the Node route is chosen.
- Here we are defining a route if the URL http://localhost:3000/Angular is selected in the browser. To the route, we are attaching a callback function which will be called when we browse to the Angular URL.
- We are using the send function to send the string “Tutorial on Angular” back to the client if the Angular route is chosen.
- This is the default route which is chosen when one browses to the route of the application – http://localhost:3000. When the default route is chosen, the message “Welcome to Guru99 Tutorials” will be sent to the client.
If the command is executed successfully, the following Output will be shown when you run your code in the browser.
Output:
From the output,
- You can clearly see that we if browse to the URL of localhost on port 3000, you will see the string ‘Welcome to Guru99 Tutorials’ displayed on the page.
- Because in our code, we have mentioned that our default URL would display this message.
From the output,
- You can see that if the URL has been changed to /Node, the respective Node route would be chosen and the string "Tutorial On Node’ is displayed.
From the output,
You can see that if the URL has been changed to /Angular, the respective Node route would be chosen and the string “Tutorial On Angular” is displayed.
Sample Web server using express.js
From our above example, we have seen how we can decide on what output to show based on routing. This sort of routing is what is used in most modern-day web applications. The other part of a web server is about using templates in Node.js.
When creating quick on-the-fly Node applications, an easy and fast way is to use templates for the application. There are many frameworks available in the market for making templates. In our case, we will take the example of the pug framework for template.
pug gets installed via the Node Package manager. This can be done by executing the following line in the command line
npm install pug
The above command requests the Node package manager to download the required pug modules and install them accordingly.
Let’s use our newly installed pug framework and create some basic templates.
Step 1) The first step is to create a pug template. Create a file called index.pug and insert the below code. Ensure to create the file in “views” folder
-
Here we are specifying that the title of the page will be changed to whatever value is passed when this template gets invoked.
-
We are also specifying that the text in the header tag will get replaced to whatever gets passed in the pug template.
在这里,我们指定页面的标题将更改为调用此模板时传递的任何值。我们还指定header标记中的文本将替换为pug模板中传递的任何内容
const express = require('express');
const app = express();
app.set('view engine', 'pug');
app.get('/', (req, res) => {
res.render('index',
{
title: 'Guru99',
message: 'Welcome'
});
});
const server = app.listen(3000, () => {
});
Code Explanation:
-
The first thing to specify in the application is “view engine” that will be used to render the templates. Since we are going to use jade to render our templates, we specify this accordingly.
在应用程序中指定的第一件事是将用于呈现模板的“视图引擎”。由于我们将使用pug渲染模板,因此我们相应地指定了它
-
The render function is used to render a web page. In our example, we are rendering the template (index.pug) which was created earlier.
渲染功能用于渲染网页。在我们的示例中,我们正在渲染先前创建的模板(index.pug)
-
We are passing the values of “Guru99” and “Welcome” to the parameters “title” and “message” respectively. These values will be replaced by the ‘title’, and ‘message’ parameters declared in the index.pug template.
我们将“ Guru99”和“ Welcome”的值分别传递给参数“ title”和“ message”。这些值将由index.pug模板中声明的’title’和’message’参数替换。
If the command is executed successfully, the following Output will be shown when you run your code in the browser.
Output:
From the output,
- We can see that the title of the page gets set to “Guru99” and the header of the page gets set to “Welcome.”
- This is because of the pug template which gets invoked in our node.js application.
Summary
-
The express framework is the most common framework used for developing Node js applications. The express framework is built on top of the node.js framework and helps in fast-tracking development of server-based applications.
express框架是用于开发Node js应用程序的最常用框架。express框架建立在node.js框架之上,可帮助快速跟踪基于服务器的应用程序的开发。
-
Routes are used to divert users to different parts of the web applications based on the request made. The response for each route can be varied depending on what needs to be shown to the user.
路由用于根据请求将用户转移到Web应用程序的不同部分。每个路线的响应可以根据需要向用户显示的内容而变化
-
Templates can be used to inject content in an efficient manner. Jade is one of the most popular templating engines used in Node.js applications.
pug是Node.js应用程序中最流行的模板引擎之一
n be varied depending on what needs to be shown to the user.
路由用于根据请求将用户转移到Web应用程序的不同部分。每个路线的响应可以根据需要向用户显示的内容而变化
-
Templates can be used to inject content in an efficient manner. Jade is one of the most popular templating engines used in Node.js applications.
pug是Node.js应用程序中最流行的模板引擎之一