express笔记

express笔记

一月 07, 2022

express是基于node.js的web开发框架

基本应用

1
2
3
4
5
6
7
8
9
10
11
const express = require('express')
const app = express()//建立一个express应用
const port = 3000

app.get('/' //路由, (req, res) => {
res.send('Hello World!')
})//app.get()接受两个参数,第一个是路由路径,第二个是处理请求的匿名函数,有两个形参,第一个代表请求,第二个代表相应

app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})//监听端口

express不仅支持

中间件

中间件是对一次请求进行多次有次序的处理,打个比方我们要验证前端发来的数据,然后通过后发送登入成功,就可以用两个方法,一个验证前端数据,一个发送数据,因为验证是在发送数据前面,就要用到中间件

1
2
3
4
5
6
7
8
9
10
11
12
13
 var express = require('express');
var app = express();
app.get('/', function(req, res, next) {
// req 修改请求
// res 响应对象
checkres//验证数据
next(); // 当前中间件函数没有结束请求/响应循环, 调用next(),
// 将控制权传递给下一个中间件函数继续往下处理,否则页面到此会被挂起
});
app.get('/end', function(req, res) {
res.send('程序到我这里就结束了,没有next方法');//发送数据
})
app.listen(3000);

使用next()就会调用下一个中间件

中间件还有种使用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var express = require('express');
var app = express();
var next= function(req, res, next) {
// req 修改请求
// res 响应对象
next(); // 当前中间件函数没有结束请求/响应循环, 调用next(),
// 将控制权传递给下一个中间件函数继续往下处理,否则页面到此会被挂起
}
app.use(next)

app.get('/end', function(req, res) {
res.send('程序到我这里就结束了,没有next方法');
})
app.listen(3000);

api

太多了,不记了直接去官网看