


A Getting Started Guide to Using the Express Framework for Node.js_node.js
Introduction to Express
npm provides a large number of third-party modules, including many web frameworks, such as Express, a lightweight web framework we will talk about in this chapter.
Express is a simple and flexible node.js web application development framework. It provides a series of powerful functions, such as: template parsing, static file serving, middleware, routing control, etc., and you can also use plug-ins or integrations Other modules help you create various web and mobile device applications. It is currently the most popular web development framework based on Node.js, and supports various templates such as Ejs and jade, so you can quickly build a website with complete functions.
Okay, let’s get started!
1. NPM installation
npm install express
2. Obtain and quote
var express = require('express'); var app = express();
Through the variable "app" we can call various methods of express. The fun has just begun, keep up the good work!
Create application
After getting to know the Express framework, we started to create our first express application.
Add the following content to our default project main file app.js:
var express = require('express'); var app = express(); app.get('/', function (request, response) { response.send('Hello World!'); }); app.listen(80);
Note: In the following courses, we will use port 80 to listen for requests.
After adding it, check the browser content through the "Test Address" in the right column. When you see the "Hello World!" content, it means that a simple express application has been created successfully.
get request
Earlier we implemented a simple express application. Now we will start to describe its specific implementation in detail. First, let’s learn the common methods of Express.
get method - handles GET requests issued by the client according to the request path.
Format:
app.get(path,function(request, response));
path is the path of the request, and the second parameter is the callback function for processing the request. There are two parameters, request and response, which represent request information and response information.
Example below:
var express = require('express'); var app = express(); app.get('/', function(request, response) { response.send('Welcome to the homepage!'); }); app.get('/about', function(request, response) { response.send('Welcome to the about page!'); }); app.get("*", function(request, response) { response.send("404 error!"); }); app.listen(80);
In the above example, the processing method of about page path, root path and all paths is specified. And inside the callback function, use the send method of the HTTP response to send a string to the browser.
Refer to the above code, try to set a get request path yourself, and then access the address through the browser to see if the request can be successful.
Middleware
Middleware is a function that processes HTTP requests and is used to complete various specific tasks, such as checking whether the user is logged in, analyzing data, and other tasks that need to be completed before the data is finally sent to the user. Its biggest feature is that after one middleware has processed it, the corresponding data can be passed to the next middleware.
2. A middleware that does not perform any operations and only passes the request object, probably like this:
function Middleware(request, response, next) { next(); }
The next in the above code is the callback function of the middleware. If it takes a parameter, it means throwing an error, and the parameter is the error text.
function Middleware(request, response, next) { next('出错了!'); }
After an error is thrown, subsequent middleware will no longer be executed until an error handling function is found. If the next method is not called, the functions registered later will not be executed.
Basic usage of all function
Different from the get function, the app.all() function can match all HTTP verbs, which means it can filter requests from all paths. If you use the all function to define middleware, it means that all requests must pass through this first. the middleware.
Format:
app.all(path,function(request, response));
As shown below, we use the all function to set the response header attributes before the request.
var express = require("express"); var app = express(); app.all("*", function(request, response, next) { response.writeHead(200, { "Content-Type": "text/html;charset=utf-8" }); //设置响应头属性值 next(); }); app.get("/", function(request, response) { response.end("欢迎来到首页!"); }); app.get("/about", function(request, response) { response.end("欢迎来到about页面!"); }); app.get("*", function(request, response) { response.end("404 - 未找到!"); }); app.listen(80);
The "*" in the above code parameters means that it is valid for all paths. This method is particularly useful when processing a specific prefix path or any path. No matter we request any path, it will go through the all function in advance.
If shown, what will happen if we skip the all function? Try it yourself?
use basic usage 1
use is express’s method of calling middleware, and it returns a function.
Format:
app.use([path], function(request, response, next){}); //可选参数path默认为"/"。
1. Use middleware
app.use(express.static(path.join(__dirname, '/')));
As above, we use the use function to call the express middleware to set the access path to the static file directory (assumed to be the root path here).
2. How to call two middlewares continuously, as shown in the following example:
var express = require('express'); var app = express(); app.use(function(request, response, next){ console.log("method:"+request.method+" ==== "+"url:"+request.url); next(); }); app.use(function(request, response){ response.writeHead(200, { "Content-Type": "text/html;charset=utf-8" }); response.end('示例:连续调用两个中间件'); }); app.listen(80);
回调函数的next参数,表示接受其他中间件的调用,函数体中的next(),表示将请求数据传递给下一个中间件。
上面代码先调用第一个中间件,在控制台输出一行信息,然后通过next(),调用第二个中间件,输出HTTP回应。由于第二个中间件没有调用next方法,所以req对象就不再向后传递了。
use基本用法2
use方法不仅可以调用中间件,还可以根据请求的网址,返回不同的网页内容,如下示例:
var express = require("express"); var app = express(); app.use(function(request, response, next) { if(request.url == "/") { response.send("Welcome to the homepage!"); }else { next(); } }); app.use(function(request, response, next) { if(request.url == "/about") { response.send("Welcome to the about page!"); }else { next(); } }); app.use(function(request, response) { response.send("404 error!"); }); app.listen(80);
上面代码通过request.url属性,判断请求的网址,从而返回不同的内容。
回调函数
Express回调函数有两个参数,分别是request(简称req)和response(简称res),request代表客户端发来的HTTP请求,request代表发向客户端的HTTP回应,这两个参数都是对象。示例如下:
function(req, res) { });
在后面的学习中,我们会经常和它打交道,牢牢记住它的格式吧!
获取主机名、路径名
今天我们就先来学习如何使用req对象来处理客户端发来的HTTP请求。
req.host返回请求头里取的主机名(不包含端口号)。
req.path返回请求的URL的路径名。
如下示例:
var express = require('express'); var app = express(); app.get("*", function(req, res) { console.log(req.path); res.send("req.host获取主机名,req.path获取请求路径名!"); }); app.listen(80);
试一试在浏览器中输入任意一个请求路径,通过req查看主机名或请求路径。
query基本用法
query是一个可获取客户端get请求路径参数的对象属性,包含着被解析过的请求参数对象,默认为{}。
var express = require('express'); var app = express(); app.get("*", function(req, res) { console.log(req.query.参数名); res.send("测试query属性!"); }); app.listen(80);
通过req.query获取get请求路径的对象参数值。
格式:req.query.参数名;请求路径如下示例:
例1: /search?n=Lenka
req.query.n // "Lenka"
例2: /shoes?order=desc&shoe[color]=blue&shoe[type]=converse
req.query.order // "desc" req.query.shoe.color // "blue" req.query.shoe.type // "converse"
试一试get请求一个带参数路径,使用“req.query.参数名”方法获取请求参数值。
param基本用法
和属性query一样,通过req.param我们也可以获取被解析过的请求参数对象的值。
格式:req.param("参数名");请求路径如下示例:
例1: 获取请求根路径的参数值,如/?n=Lenka,方法如下:
var express = require('express'); var app = express(); app.get("/", function(req, res) { console.log(req.param("n")); //Lenka res.send("使用req.param属性获取请求根路径的参数对象值!"); }); app.listen(80);
例2:我们也可以获取具有相应路由规则的请求对象,假设路由规则为 /user/:name/,请求路径/user/mike,如下:
app.get("/user/:name/", function(req, res) { console.log(req.param("name")); //mike res.send("使用req.param属性获取具有路由规则的参数对象值!"); });
PS:所谓“路由”,就是指为不同的访问路径,指定不同的处理方法。
看了上面的示例,试一试使用req.param属性解析一个请求路径对象,并获取请求参数值。
params基本用法
和param相似,但params是一个可以解析包含着有复杂命名路由规则的请求对象的属性。
格式:req.params.参数名;
例1. 如上课时请求根路径的例子,我们就可以这样获取,如下:
var express = require('express'); var app = express(); app.get("/user/:name/", function(req, res) { console.log(req.params.name); //mike res.send("使用req.params属性获取具有路由规则的参数对象值!"); }); app.listen(80);
查看运行结果,和param属性功能是一样的,同样获取name参数值。
例2:当然我们也可以请求复杂的路由规则,如/user/:name/:id,假设请求地址为:/user/mike/123,如下:
app.get("/user/:name/:id", function(req, res) { console.log(req.params.id); //"123" res.send("使用req.params属性复杂路由规则的参数对象值!"); });
对于请求地址具有路由规则的路径来说,属性params比param属性是不是又强大了那么一点点呢!
send基本用法
send()方法向浏览器发送一个响应信息,并可以智能处理不同类型的数据。格式如下: res.send([body|status], [body]);
1.当参数为一个String时,Content-Type默认设置为"text/html"。
res.send('Hello World'); //Hello World
2.当参数为Array或Object时,Express会返回一个JSON。
res.send({ user: 'tobi' }); //{"user":"tobi"} res.send([1,2,3]); //[1,2,3]
3.当参数为一个Number时,并且没有上面提到的任何一条在响应体里,Express会帮你设置一个响应体,比如:200会返回字符"OK"。
res.send(200); // OK res.send(404); // Not Found res.send(500); // Internal Server Error
send方法在输出响应时会自动进行一些设置,比如HEAD信息、HTTP缓存支持等等。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We
