• 2023 全栈工程师 Node.Js 服务器端 web 框架 Express.js 详细教程(更新中)


    Express 框架概述

    Express 是一个基于 Node.js 平台的快速、开放、极简的Web开发框架。它本身仅仅提供了 web 开发的基础功能,但是通过中间件的方式集成了外部插件来处理HTTP请求,例如 body-parser 用于解析 HTTP 请求体,compression 用于压缩 HTTP 响应,cookie-parse 用于解析 cookie 数据,cors 用于处理跨域资源请求,Morgan 用于 http 请求日志。这使得 Express 本身变得更加灵活和简单。

    Express 官方网站:https://expressjs.com/

    在这里插入图片描述

    下载安装 Express 框架模块包

    npm install express
    
    • 1

    Express 初体验案例

    const express = require('express')
    const app = express()
    
    app.get('/', function (req, res) {
    	res.send('Hello World')
    })
    
    app.listen({port: 3000, hostname: '127.0.0.1'}, () => {
        console.log('http://127.0.0.1:3000/')
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    获取 request 请求数据

    app.get('/index', function (req, res) {
        console.log(req.method)
        console.log(req.url)
        console.log(req.httpVersion)
        console.log(req.headers)
        console.log(req.path)
        console.log(req.query)
        console.log(req.ip)
        console.log(req.params)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    response 响应配置

    Node.Js 原生响应 response

    app.get("/response", (req, res) => {
        res.statusCode = 200;
        res.statusMessage = 'love'
        res.setHeader('xxx', 'yyy')
        res.write('hello express')
        res.end('response')
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    Express 响应 response

    app.get("/response", (req, res) => {
        res.status(200);
        res.set('aaa', 'bbb')
        res.send('hello Express')
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5

    配置路由参数

    app.get("/data/:id", (req, res) => {
        console.log(req.params.id)
    })
    
    • 1
    • 2
    • 3

    重定向 redirect

    app.get("/redirect", (req, res) => {
        res.redirect("http://www.baidu.com/")
    })
    
    • 1
    • 2
    • 3

    下载服务器资源 download

    app.get("/download", (req, res) => {
        res.download(__dirname + "/test.mp4")
    })
    
    • 1
    • 2
    • 3

    响应 Json 格式数据

    app.get("/json", (req, res) => {
        res.json({name: 'helloworld', password: "helloworld"})
    })
    
    • 1
    • 2
    • 3

    测试结果

    在这里插入图片描述

    Express 中间件

    在 Express 中, 使用 app.use 或者 app.METHOD 注册的中间件叫做应用级中间件。

    全局中间件:给每个路由规则都添加中间件处理函数

    app.use(function (req, res, next) {
    	console.log('我是一个全局中间件, 影响所有的路由规则')
    })
    
    • 1
    • 2
    • 3

    局部中间件:给某一个特定的路由规则添加中间件处理函数

    app.use('/users', function (req, res, next) {
    	console.log(`这里是一个局部中间件, 只影响/users路由`)
    	next()
    })
    
    • 1
    • 2
    • 3
    • 4

    路由中间件

    express.Router()对象也可以注册中间件。使用 router.use 或者 router.METHOD 注册的中间件叫做路由级中间件。

    var app = express()
    var router = express.Router()
     
    router.use(function (req, res, next) {
    	console.log('Time:', Date.now())
    	next()
    })
    router.get('/users/', function(req, res) {
    	res.send('hello')
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    静态资源中间件

    如果要在网页中加载静态文件(比如样式表、图片等)就需要另外指定一个存放静态文件的目录。注意 index.html 文件是默认打开的资源。如果静态资源与路由规则同时匹配,谁先匹配谁就响应。路由响应动态资源,静态资源中间件响应静态资源。

    app.use(express.static(__dirname + '/public'))
    
    • 1

    获取请求体数据

    解析 querystring 请求体数据

    const bodyparser = require('body-parser')
    app.use(bodyparser.urlencoded({ extended: true }))
    app.post("/post", (req, res) => {
        console.log(req.body)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5

    解析 json 请求体数据

    const bodyparser = require('body-parser')
    app.use(bodyparser.json())
    app.post("/post", (req, res) => {
        console.log(req.body)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    { username: '123', password: '123' }
    
    • 1

    Express.Router

    Express 4.0 路由器功能成了一个单独的组件Express.Router。它好像小型的 express 应用程序一样,有自己的use、get、param 和 route 方法。

    首先,Express.Router 是一个构造函数,调用后返回一个路由器实例。然后,使用该实例的HTTP动词方法,为不同的访问路径,指定回调函数;最后,挂载到某个路径。

    var router = express.Router();
    
    router.get('/', function(req, res) {
    	res.send('首页');
    });
    
    router.get('/about', function(req, res) {
    	res.send('关于');
    });
    
    app.use('/', router);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    定义了两个访问路径,然后将它们挂载到根目录。如果最后一行改为app.use(‘/app’, router),则相当于为/app和/app/about这两个路径,指定了回调函数。这种路由器可以自由挂载的做法,为程序带来了更大的灵活性,既可以定义多个路由器实例,也可以为将同一个路由器实例挂载到多个路径。

    app.route 实例

    假定 app 是 Express 的实例对象,Express 4.0为该对象提供了一个route属性。app.route 实际上是 express.Router() 的缩写形式,除了直接挂载到根路径。因此对同一个路径指定 get 和 post 方法的回调函数,能写成链式形式。

    app.route('/login')
    	.get(function(req, res) {
    		res.send('this is the login form');
    	})
    	.post(function(req, res) {
    		console.log('processing');
    		res.send('processing the login form!');
    	});
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
  • 相关阅读:
    单片机:步进电机(内含:1 步进电机简介+2 步进电机工作原理+ 3 步进电机技术指标 +4. 软件设计+5.原始代码+6.实验现象)
    linux top命令按内存/CPU排序显示
    CSP-J 2022 第一轮试题
    LeetCode·每日一题·828.统计子串中的唯一字符·数学
    UiPath快捷键
    燃气仓储革命:数字孪生系统领航未来
    marven项目打包第三方jar包
    Python的logging模块Demo
    Android:viewPage+Fragment实现模拟微信首页
    求解多旅行推销员问题的两部分编码遗传算法算子
  • 原文地址:https://blog.csdn.net/qq_47452807/article/details/134279337