Table of contents
1. Introduction to Express Framework
2. Create a basic web server with express
② Import the routing module and register the route
③ Start the server and access the api
1. Get the query string in the url and dynamically return the content
2. Get url dynamic parameters and dynamically return content
5. Things to note about middleware
① Application-level middleware
1. Introduction to Express Framework
Express is a fast, open, and minimalist web development framework based on the Node.js platform. To put it simply, Express functions similarly to the http module. It not only retains the basic API of http, but also encapsulates some new methods, making it more efficient to develop than the http module. Express also provides middleware functions, including built-in middleware, third-party middleware and custom middleware, which can be used to intercept requests and responses and extend the functions of requests and responses.
2. Installation and use
1.Installation
In the current project directory, run the following command on the terminal:
npm install express
2. Create a basic web server with express
//1.导入Express
const express = require('express')
//2.创建Web服务器
const app = express()
//3.启动服务器
app.listen(8080,()=>{
console.log('express is running at http://127.0.0.1:8080')
})
3. Express routing
1. Routing concept
Routing refers to determining how an application responds to client requests for a specific endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, etc.).
Route definitions take the following structure:
app.METHOD(PATH, HANDLER)
//app是express实例对象
//METHOD是HTTP请求方法,如get、post
//PATH是服务器路径
//HANDLER是回调处理函数
2. Create basic routes
①.Create a simple get route
app.get("/user", (req, res) => { // 监听get请求'/user'
// 返回JSON对象
res.status(200).send({ name: "zhangsan", age: 20, height: 180 });
});
② Create a simple post route
app.post("/list", (req, res) => { //监听post请求'/list'
// 返回成功信息
res.send({ code: 200, message: "success" });
});
3.Routing modularization
Because the file is large, it is not recommended to mount the route directly on the app. In order to facilitate management, we extract the separate routing module and call express.Router() to create the routing object.
①Create router.js file
// 1.导入express
const express = require("express");
// 3.调用express.Router()创建路由对象
const router = express.Router();
// 3.挂载get请求
router.get("/user", (req, res) => {
res.status(200).send({ name: "zhangsan", age: 20, height: 180 });
});
// 4.挂载post请求
router.post("/list", (req, res) => {
res.send({ code: 200, message: "success" });
});
// 5.导出路由对象
module.exports = router
② Import the routing module and register the route
//1.导入Express
const express = require("express");
//2.创建Web服务器
const app = express();
//3.导入路由模块
const router = require("./router");
//4.注册路由模块,访问时带'/api'前缀
app.use('/api',router);
//5.启动服务器
app.listen(8081, () => {
console.log("express is running at http://127.0.0.1:8081");
});
③ Start the server and access the api
4. How to obtain parameters
1. Get the query string in the url and dynamically return the content
app.get("/getUser", (req, res) => {
const { query } = req; // 获取req.query:解析url中的查询字符串,并返回一个对象
let result = {};
if (query.name == "zhangsan") { // 根据name动态返回信息
result = { code: 200, message: "success" };
} else {
result = { code: 404, message: "failure" };
}
res.send(result);
});
① When the name is zhangsan
② When the name is lisa
2. Get url dynamic parameters and dynamically return content
app.get("/getBMI/:height/:weight", (req, res) => {
const { params } = req; // 获取动态参数
let bmi = params.weight / Math.pow(params.height / 100, 2); // 计算传入的动态参数
let result = getBmi(bmi); // 调用获取bmi方法
res.send(result); // 返回相应内容
});
function getBmi(bmi) { // 获取bmi
if (bmi <= 18.4) {
return { code: 200, message: "偏瘦", bmi: bmi };
} else if (bmi > 18.4 && bmi < 24) {
return { code: 200, message: "正常", bmi: bmi };
} else if (bmi >= 24 && bmi < 28) {
return { code: 200, message: "过重", bmi: bmi };
} else if (bmi >= 28) {
return { code: 200, message: "肥胖", bmi: bmi };
} else {
return { code: 404, message: "请输入正确内容" };
}
}
5. Express middleware
1. Middleware concept
Middleware is an intermediate component that works between the client and the server. It is mainly used to intercept requests and responses and extend the functions of requests and responses.
2.Middleware workflow
3. Create a middleware
const mw = function(req,res,next){
console.log("我是一个中间件")
next() //必须调用next(),表示流转关系转入下一个中间件或路由
}
4. Use of middleware
① Global use
Multiple middlewares share the same reg and res. Based on this feature, we can uniformly add custom attributes or methods to reg or res objects in upstream middleware for use by downstream middleware or routing.
const mw = function (req, res, next) {
req.createTime = new Date().toLocaleString(); //共享createTime
next();
};
app.use(mw); // 注册全局中间件
app.get("/user", (req, res) => {
res.send("创建时间为" + req.createTime); // 获取全局中间件createTime参数
});
Note: There can be multiple global middlewares, which are called in sequence according to the registration order.
app.use(function (req, res, next) {
console.log("我是第一个全局中间件");
next();
});
app.use(function (req, res, next) {
console.log("我是第二个全局中间件");
next();
});
app.get("/user", (req, res) => {
res.send("调用/user");
});
② Use locally
Partial middleware is mounted in routing and only takes effect on the current routing interface.
const mw = function (req, res, next) {
req.createTime = new Date().toLocaleString(); //共享时间
next();
};
app.get("/user", mw, (req, res) => {
res.send("userApi创建时间为" + req.createTime); // 可以获取createTime
});
app.get("/id", (req, res) => {
res.send("idApi创建时间为" + req.createTime); // 无法获取createTime,返回undefine
});
Mount multiple local middleware [ mw1,mw2,etc ] or mw1,mw2,etc
app.get("/user", [mw1, mw2, etc], (req, res) => {
res.send("调用/user")
})
app.get("/user", mw1, mw2, etc, (req, res) => {
res.send("调用/user")
})
5. Things to note about middleware
① Be sure to register middleware before routing
②Requests sent from the client can be processed by calling multiple middlewares continuously.
③After executing the business code of the middleware, don’t forget to call the next() function
④In order to prevent code logic confusion , do not write additional code after calling the next() function.
⑤When multiple middlewares are called continuously, req and res objects are shared between multiple middlewares.
6. Middleware classification
Officially divides middleware into five categories
① Application-level middleware
Middleware that is bound to the app instance through app.use(), app.get(), app.post(), etc. is called application-level middleware.
Application-level middleware can call next('route') to jump to the next route. Note: next('route') only works on app.METHOD() or router.METHOD()
app.get("/user/:id",function (req, res, next) {
// 如果id为0则跳到下一个路由
if (req.params.id === "0") next("route");
// 否则控制权交给堆栈中的下一个中间件函数
else next();
},
function (req, res, next) {
// 返回regular
res.send("regular");
}
);
app.get("/user/:id", function (req, res, next) {
// id为0时返回special
res.send("special");
});
② Routing level middleware
Middleware bound to express.Router() instances is called routing-level middleware. Usage is no different from application-level middleware.
Route-level middleware can call next('route') to jump to the next route.
router.get('/user/:id', function (req, res, next) {
// 如果id为0则跳到下一个路由
if (req.params.id === '0') next('route')
// 否则控制权交给堆栈中的下一个中间件函数
else next()
}, function (req, res, next) {
// 返回regular
res.send('regular')
})
// id为0时返回special
router.get('/user/:id', function (req, res, next) {
console.log(req.params.id)
res.send('special')
})
③ Error level middleware
The middleware used to capture abnormal errors that occur in the project and prevent the project from crashing abnormally is called error-level middleware.
Error-level middleware can only capture errors in previous routes and is generally registered for use at the end, contrary to other middleware.
app.get("/", function (req, res, next) {
throw new Error("服务器异常");
res.send("special");
});
const error = function (err, req, res, next) {// 只能捕获前面路由的错误,一般放在最后
console.log(err.message);
res.status(500).send(err.message);// 返回500 错误信息
};
④ Built-in middleware
Express has three commonly used middleware built-in : express.static , express.json , and express.urlencoded .
1)express.static
Function: Host static resources, such as html, img, css, etc.
Specific steps are as follows:
Ⅰ.Create a file folder and create a new index.html in the folder
Ⅱ. Hosting static files
Access without mounting path prefix
app.use(express.static("file"))
Mount path prefix access
app.use("/file", express.static("file"))
Ⅲ.Access static resources
Note: If you want to host multiple static resources, you need to call the express.static() function multiple times.
When accessing static resources, they will be searched according to the order in which they were added.
2)express.json
Function: Parse JSON format data
app.use(express.json())
3)express.urlencoded
Function: Parse URL-encoded data
app.use(express.urlencoded( extended:false ))
⑤ Third-party middleware
Middleware that is not officially built into Express but developed by a third party is called third-party middleware. To use third-party middleware, you need to download the install first, import the corresponding module, and finally call app.use() to register for use.
e.g. cookie-parser
1) Install cookie-parser
npm install --save-dev cookie-parser
2) Import and register for use
const cookieParser = require("cookie-parser");
app.use(cookieParser());
3) Set cookies
res.cookies('key','value',option)
4) Get cookies
console.log(req.signedCookies['key'])
6. Build the server
1.Install express
npm install express
2. Write routing router.js
// 1.导入express
const express = require("express");
// 2.调用express.Router()创建路由对象
const router = express.Router();
// 3.挂载路由
router.get('/get',(req,res)=>{
const {query} = req // get请求获取query
res.send({
status:200,
message:"get success",
data:query
})
})
router.post('/post',(req,res)=>{
const {body} = req // post请求获取body
res.send({
status:200,
message:"post success",
data:body
})
})
// 4.导出路由对象
module.exports = router
3. Write server server.js
//1.导入Express
const express = require("express");
//2.创建Web服务器
const app = express();
//3.注册urlencoded中间件,获取post请求体
app.use(express.urlencoded({extended:false}))
//4.导入路由对象
const router = require("./router");
//5.挂载路由
app.use('/api',router);
//6.启动服务器
app.listen(8081, () => {
console.log("express is running at http://127.0.0.1:8081");
});
4. Start the server
Run this command in the upper-level directory of server.js
node server