express

Fast, unopinionated, minimalist web framework for Node.js
引自 Express 官方网站

Java? Tomcat!
PHP? Apache!
.Net? IIS!
Node.js? Yum ... express?

每一种主流的 web 开发语言,都有度身定制的应用容器。然而,Node.js 发展至 7.0,却依旧孑然一身。幸好,它还有 express。注意:express ≠ Express!

在线资源

从 express Generator 开始

# 安装初始化命令行工具
npm install express-generator

# 查看命令帮助
express -h
# 注意:这里生成的 express 命令,可用于初始化基于 Express 框架的应用,但它不是框架本身。

# 创建(如不存在)并初始化应用目录
express myExpressApp

# 切换到应用目录
cd myExpressApp
# 以调试模式启动应用
PORT=8080 DEBUG=1 ./bin/www
# 或,直接启动
npm start

如果不指定启动端口,通过 express Generator 创建的应用的默认端口为 3000:
localhost3000

常用中间件

Express 官方将中间件(middleware)分为以下几类:

  • Application-level middleware

  • Router-level middleware

  • Error-handling middleware

    Error-handling middleware always takes four arguments. You must provide four arguments to identify it as an error-handling middleware function.

    // Express 是通过中间件函数的形参数量来判断这是否是一个错误处理中间件。
    app.use(function (err, req, res, next) {
       console.error(err.stack)
       res.status(500).send('Something broke!')
    });
    
  • Built-in middleware

    With the exception of express.static, all of the middleware functions that were previously included with Express’ are now in separate modules.

    Express 4.x 起已经实现了完全的模块化,内置中间件仅保留 express.static() 一个。

  • Third-party middleware

Middleware: body-parser

https://www.npmjs.com/package/body-parser

results matching ""

    No results matching ""