


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缓存支持等等。

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.


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

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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function