文章目录
Express 安装
基本使用
// 1、导入 express 模块
const express = require('express')
// 2、创建 web 服务器实例
const app = express()
app.get('/user', (req, res, next) => {
// 发送 json 对象给客户端
res.send({
name: 'ahcheng', age: 18 })
})
app.post('/user', (req, res, next) => {
// 发送文本内容给客户端
res.send('hhhh')
})
// 3、调用 app.listen( 端口号, 启动服务器后调用的回调函数 ),启动服务器,
app.listen(80, ()=> {
console.log("express server running at http://127.0.0.1:80")
})
中间件
Express是一个路由和中间件的Web框架,它本身的功能非常少:**Express应用程序本质上是一系列中间件函数的调用;**express 是一串中间件工具链。
中间件是什么呢?中间件的本质是传递给express的一个回调函数;
这个回调函数接受三个参数:
- 请求对象(request对象);
- 响应对象(response对象);
- next函数(在express中定义的用于执行下一个中间件的函数);
- 没有 next 则后续中间件没有执行权。只有上一个中间件有 next,则后续中间件路径匹配上了就会执行
中间件中可以执行哪些任务呢?
- 执行任何代码;
- 更改请求(request)和响应(response)对象;
- 结束请求-响应周期(返回数据);
- 调用栈中的下一个中间件;
res.end 在 next 之前执行,并不会报错。因为它只代表服务器响应结束了,后续无法再进行 http 相关的操作。但是中间件并没有结束,所以后续的中间件能继续执行。代码不报错。
如果当前中间件功能没有结束请求-响应周期,则必须调用 next() 将控制权传递给下一个中间件功能,否则,请求
将被挂起。
编写中间件
如何将一个中间件应用到我们的应用程序中呢?
- express主要提供了两种方式:
app/router.use
和app/router.methods
;- 可以是 app,也可以是router,router我们后续再学习:
- methods指的是常用的请求方式,比如: app.get或app.post等;
学习use的用法,因为methods的方式本质是use的特殊情况:
- use 和 methods 方法一样,也可以接收 url 进行匹配。如果没有传入 url 路径,则会匹配所有的 url。
- use 和 methods 都可以连续定义多个中间件,这些中间件的执行也是按定义顺序来的。
- 在 use 中定义的中间件也叫全局中间件;在 methods 中定义的为局部中间件。
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log("common middleware 01");
next();
});
app.get('/home', (req, res, next) => {
console.log("home path and method middleware 01");
next();
})
app.get("/home", (req, res, next) => {
console.log("home path and method middleware 02");
next();
}, (req, res, next) => {
console.log("home path and method middleware 03");
next();
}, (req, res, next) => {
console.log("home path and method middleware 04");
res.end("home page");
});
app.listen(8000, () => {
console.log("express初体验服务器启动成功~");