• express 快速教程


    阅读 express 官方文档的记录.

    hello world example

    var express = require('express')
    var app = express()
    
    app.get('/', function(req, res) {
        res.send('Hello World')
    })
    
    app.listen(3000, function() {
        console.log('Example app listening on port 3000!')
    })
    

    Routing

    路由定义:
    app.METHOD(PATH, HANDLER), METHOD 为 HTTP 请求方法, PATH 为路由路径, HANDLER 路由回调函数, 参数为 req, res.
    METHOD 还可以为 all, 它的回调函数多一个 next, 作为中间件的功能.

    Route paths

    路由路径可以为字符串, 字符串模式(?, +, *, () 分别对应正则)以及正则表达式

    Route parameters

    路由参数是 URL 中的被捕获的特殊位置的片段, 可以通过 req.params 对象获取

    app.get('/users/:userId/books/:bookId', function(req, res) {
        url = "http://localhost:3000/users/34/books/8989"
        req.params = {
            userId: "34",
            bookId: "8989"
        }
    })
    
    // 路径参数名字只能为[A-Za-z0-9_]中的字符
    // 因此可以使用 '-', '.' 提供一些特殊的功能
    app.get('/flights/:from-:to', function(req, res) {
        url = 'http://localhost:3000/flights/SH-BJ'
        req.params = {
            from: 'SH',
            to: 'BJ'
        }
    })
    app.get('/plantae/:genus.:species', function(req, res) {
        url = 'http://localhost:3000/plantae/Prunus.persica'
        req.params = {
            genus: 'Prunus',
            species: 'persica'
        }
    })
    

    Route handlers

    可以提供多个路由回调函数, 其中一些可以提供类似中间件的功能处理请求, 但是必须要调用 next 以调用下一个回调函数.

    Response methods

    express 的路由回调函数中的 res 必须调用一下方法以结束请求响应:

    • download
    • end
    • json()
    • jsonp
    • redirect
    • render
    • send
    • sendFile
    • sendStatus

    app.route()

    使用 app.route() 可以对一个路由链式调用不同的 HTTP 请求

    app.route('/book')
        .get(function(req, res) {
            res.send('Get a random book')
        })
        .post(function(req, res) {
            res.send('Add a book')
        })
        .put(function(req, res) {
            res.send('Update the book')
        })
    

    express.Router

    express.Router 可以创建一个路由处理模块

    var express = require('express');
    var router = express.Router();
    
    // middleware that is specific to this router
    router.use(function timeLog(req, res, next) {
      console.log('Time: ', Date.now());
      next();
    });
    // define the home page route
    router.get('/', function(req, res) {
      res.send('Birds home page');
    });
    // define the about route
    router.get('/about', function(req, res) {
      res.send('About birds');
    });
    
    module.exports = router;
    

    以中间件的方式使用 express.Router

    var birds = require('./birds')
    app.use('/birds'', birds)
    

    中间件

    express 中的中间件就是处理 req, res, next 的函数, 中间件函数一般处理模式为:

    • 执行任意代码
    • 对 req 和 res 进行修改
    • 结束 req - res cycle
    • next 调用下一个中间件

    app 级中间件

    app.use 以使用中间件

    app.use(function(req, res, next) {
        // some code
        next()
    })
    
    // 对特定路由使用中间件
    app.use('/user', function(req, res, next) {
        // some code
        next()
    })
    

    Router 级中间件

    Router 级中间件的使用方法和 app 级的相似, 只不过中间件函数绑定在 express.Router 对象上

    错误处理中间件

    错误处理中间件函数与普通中间件的区别是错误处理多一个参数

    app.use(function(err, req, res, next) {
      console.error(err.stack);
      res.status(500).send('Something broke!');
    });
    

    内置中间件

    从 express 4.0 版本起, 内置中间件只有一个 express.static

    Static

    express 内置 express.static(root, ['options']) 中间件处理静态文件.

    app.use(express.static('public')) // Express 使用相对路径, 因此 public 不需要在 url 中
    app.use(express.static('files')) // 可以使用多个静态中间件, 按照先后顺序查找文件
    app.use('/static', express.static('public')) // 添加静态路径到 url 中
    

    第三方中间件

    第三方中间件列表

    模版

    express 默认的模版引擎为 Pug

    设置

    app.set('views', './views') // 设置模版文件所在目录
    app.set('view engine', 'pug') // 如果需要使用其他模版
    

    使用

    // 读取模版目录中的 filename 文件, 用 obj 替换模版中的变量
    res.render(filename, obj)
    

    Debug

    代理设备

  • 相关阅读:
    flask_日期和时间
    使用SQLAlchemy对博客文章进行分页
    P2725 邮票 Stamps
    P2679 子串
    P3396 哈希冲突
    P1754 球迷购票问题
    P1504 积木城堡
    P1244 青蛙过河
    CSP-S 2019 考试分析
    2019.11.11 模拟赛 T2 乘积求和
  • 原文地址:https://www.cnblogs.com/wbin91/p/5918208.html
Copyright © 2020-2023  润新知