express框架

  • 官方文档

  • Express是目前流行的基于Node.js运行环境的Web应用程序开发框架,它简洁且灵活,为Web应用程序提供了强大的功能。Express提供了一个轻量级模块,类似于jQuery(封装的工具库),它把Node.jsHTTP模块的功能封装在一个简单易用的接口中,用于扩展HTTP模块的功能,能够轻松地处理服务器的路由、响应、CookieHTTP请求的状态。

  • Express的优势:

    1. 简洁的路由定义方式。
    2. 简化HTTP请求参数的处理。
    3. 提供中间件机制控制HTTP请求。
    4. 拥有大量第三方中间件。
    5. 支持多种模版引擎。

安装express框架

// 项目初始化
npm init -y
// 安装
npm install express --save

创建最基本的服务器

  • index.js
// express框架 - 创建最简单的服务器

// 1.引入express框架
const express = require('express')

// 2.创建app服务器
const app = express()

// 3.发送请求
app.get('/',(req,res)=>{
// 不再需要独立设置响应头,能够自动解析要发送的东西,如接口数据和html片段等
// 这里使用了res.send方法取代了write()和end()方法(但是也可以使用)
// res.send('你好! express!!')

// 发送html片段
// res.send(`
// <html>
// <h1>hello! express!</h1>
// </html>
// `)

// 发送接口数据
res.send(
{
name:'lam',
age:'100'
}
)
}).listen(3000 , ()=>{
console.log('服务器已启动! 端口3000正在监听...');
})

基本路由

  • 路由是指如何定义应用的端点(URIs)以及如何响应客户端的请求。
  • 路由是由一个 URI、HTTP 请求(GET、POST等)和若干个句柄组成,它的结构如下: app.METHOD(path, [callback...], callback), appexpress 对象的一个实例, METHOD 是一个 HTTP 请求方法, path 是服务器上的路径, callback 是当路由匹配时要执行的函数。

路由的请求路径支持三种方式:字符串模式,纯字符串以及正则表达式

// 1.纯字符串[常用]('/home', '/random.text'..等)
app.get('/home',(req,res)=>{
// 不再需要独立设置响应头,能够自动解析要发送的东西,如接口数据和html片段等
// 这里使用了res.send方法取代了write()和end()方法(但是也可以使用)
res.send('你好! express!!')
})

// 2.字符串模式
// 匹配 acd 和 abcd
app.get('/ab?cd', function(req, res) {
res.send('ab?cd');
});

// 匹配 /ab/任何东西,如111,222,:id表示占位符,后面可以跟任何东西
app.get('/ab/:id', function(req, res) {
res.send('aaaaaaa');
});

// 匹配 abcd、abbcd、abbbcd等
app.get('/ab+cd', function(req, res) {
res.send('ab+cd');
});

// 匹配 abcd、abxcd、abRABDOMcd、ab123cd等
app.get('/ab*cd', function(req, res) {
res.send('ab*cd');
});

// 匹配 /abe 和 /abcde
app.get('/ab(cd)?e', function(req, res) {
res.send('ab(cd)?e');
});

// 3.正则表达式模式
// 匹配任何路径中含有 a 的路径:
app.get(/a/, function(req, res) {
res.send('/a/');
});

// 匹配 fly结尾,
app.get(/.*fly$/, function(req, res) {
res.send('/.*fly$/');
});

回调函数

  • express路由可以为请求处理提供多个回调函数(我们姑且就可以将这些回调函数成为中间件),其行为类似 中间件。唯一的区别是这些回调函数有可能调用 next('route') 方法而略过其他路由回调函数。可以利用该机制为路由定义前提条件,如果在现有路径上继续执行没有意义,则可将控制权交给剩下的路径。

  • 使用多个回调函数处理路由(记得指定 next 对象):

app.get('/example/b', (req, res, next)=>{
console.log('response will be sent by the next function ...');
next();
}, function (req, res) {
res.send('Hello from B!');
});
  • 使用回调函数数组处理路由:
var cb0 = function (req, res, next) {
console.log('CB0')
next()
}

var cb1 = function (req, res, next) {
console.log('CB1')
next()
}

var cb2 = function (req, res) {
res.send('Hello from C!')
}

app.get('/example/c', [cb0, cb1, cb2])
  • 混合使用函数和函数数组处理路由:
var cb0 = function (req, res, next) {
console.log('CB0')
next()
}

var cb1 = function (req, res, next) {
console.log('CB1')
next()
}

app.get('/', [cb0, cb1], (req, res, next)=>{
console.log('response will be sent by the next function ...')
next()
}, function (req, res) {
res.send('Hello from D!')
})
  • 这里结果:CB0 => CB1 => response will be sent by the next function ...