Express 开发环境

什么是 Express 开发环境

完整的 Express 本地开发环境包括 Nodejs、NPM 包管理器和 Express 应用生成器(可选)。

Node 和 NPM 包管理器可以用二进制包、安装程序或系统包管理器一并安装(下文将介绍)。然后在开发每个 Express web 应用时,由 NPM 针对当前应用将 Express(以及模板引擎、数据库驱动程序、身份验证中间件、静态文件托管中间件等其他库)作为依赖项进行安装。

典型的开发环境中还需要一些外围工具,包括用于编写代码的 文本编辑器 或 IDE,用于代码控制管理的工具(比如代码版本控制工具 Git)。

什么是 Node?

Node(正式名称 Node.js)是一个开源的、跨平台的运行时环境,有了它,开发人员可以使用 JavaScript 创建各种服务器端工具和应用程序。此运行时主要用于浏览器上下文之外(即可以直接运行于计算机或服务器操作系统上)。据此,该环境省略了一些浏览器专用的 JavaScript API,同时添加了对更传统的 OS API(比如 HTTP 库和文件系统库)的支持。

Node 为优化 web 应用的吞吐量和扩展度而生,对常见的 web 开发问题是一套绝佳方案(比如实时 web 应用)。代码还是熟悉的JavaScript,这意味着在客户端和服务器端“上下文切换”的时间成本更低。

Node 包管理工具(node package manager,NPM)提供了数十万个可重用的工具包。它还提供了一流的依赖解决方案,可实现自动化工具链构建。

Node API 文档 NodeJS API

Web 框架

Node 本身并不支持其他常见的 web 开发任务。如果需要进行一些具体的处理,比如运行其他 HTTP 动词(比如 GET、POST、DELETE 等)、分别处理不同 URL 路径的请求(“路由”)、托管静态文件,或用模板来动态创建响应,那么可能就要自己编写代码了,亦或使用 web 框架,以避免重新发明轮子。

Express 是最流行的 Node 框架,是许多其他流行 Node 框架 的底层库。它提供了以下机制:

  • 为不同 URL 路径中使用不同 HTTP 动词的请求(路由)编写处理程序。

  • 集成了“视图”渲染引擎,以便通过将数据插入模板来生成响应。

  • 设置常见 web 应用设置,比如用于连接的端口,以及渲染响应模板的位置。

  • 在请求处理管道的任何位置添加额外的请求处理“中间件”。

虽然 Express 本身是极简风格的,但是开发人员通过创建各类兼容的中间件包解决了几乎所有的 web 开发问题。这些库可以实现 cookie、会话、用户登录、URL 参数、POST 数据、安全头等功能。可在 Express 中间件 网页中找到由 Express 团队维护的中间件软件包列表(还有一张流行的第三方软件包列表)。

在这里插入图片描述

传统的数据驱动型网站中,web 应用是用于等待来自浏览器(或其他客户端)的 HTTP 请求的。当 web 应用收到一个请求时,会根据 URL 的模式,以及 POST 数据和 GET 数据可能包含的信息,来解析请求所需的功能。根据请求的内容,web 应用可能会从数据库读或写一些信息,等等操作来满足请求。随后,web 应用会返回给浏览器一个响应,通常是动态生成一页 HTML,在页面中用所取得的信息填充占位符。

使用 Express 可以调用特定 HTTP 动词(GET, POST, SET等)函数和 URL 模式(“路由”)函数,还可以指定模板(“视图”)引擎的种类、模板文件的位置以及渲染响应所使用的模板。可以使用 Express 中间件来添加对 cookie、会话、用户、获取 POST/GET 参数,等。可以使用 Node 支持的任何类型数据库(Express 本身没有定义任何数据库行为)。

使用 NPM

构建 Node 应用过程中,NPM 是除了 Node 本身之外最重要的工具。可用于获取应用开发、测试以及生产所需的所有包(JavaScript 库)。也可运行开发过程中使用的测试单元和工具。

以 Node 的角度来看,Express 只是一个用 NPM 安装、供人使用的包而已。

可以用 NPM 手动逐个安装所需包。但通常可用 package.json 文件来管理依赖。把每个依赖以一个 JavaScript“包”的形式(其中包括名称、版本、描述,初始执行文件、生产依赖,开发依赖、支持的 Node 版本,等等)罗列在这个文件中。package.json 文件包含 NPM 获取和运行应用程序所需的所有内容(在编写可重用的库时,可以用它把包上传到 NPM 仓库中供其他用户使用)。

添加依赖项
下面介绍用 NPM 下载包、将包保存进工程依赖树,以及在 Node 应用中调用包的方法和步骤。

现在来讲解获取和安装 Express 包的步骤。稍后解释为什么可以直接对 Express 包(乃至其他包)使用 Express 应用生成器。这段对理解 NPM 的工作原理和应用生成器的工作机制有一定的帮助。

首先为新应用创建一个目录,并进入它:

mkdir first-express-project
cd first-express-project

然后,使用 NPM 的 init 命令为应用创建一个 package.json 文件。这个命令将请求一系列的信息,包括应用的名称和版本,程序初始进入点的文件名(默认为 index.js)。现在先接受默认信息即可:

npm init

This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help init` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (first-express-project)
version: (1.0.0) 
description: express test
entry point: (index.js) 
test command: 
git repository: 
keywords: 
author: 
license: (ISC) 
About to write to /Users/jwdmac2/Desktop/2023/web-projects/first-project/first-express-project/package.json:

{
  "name": "first-express-project",
  "version": "1.0.0",
  "description": "express test",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this OK? (yes) 

package name:       项目名称       例如: test
version:          版本         例如:1.0.1
description:       描述信息       例如:这是一个测试项目
entry point:       项目入口       例如:main.js
test command:       测试命令       可跳过
git repository:     github仓库地址   可跳过
keywords:         关键字       可跳过
author:          作者        写上自己的署名
license: (ISC)      软件开源许可证   可跳过

Is this OK? (yes)     创建确认      yes

npm init -y

-y 的含义:yes的意思,在init的时候省去了敲回车的步骤,生成的默认的package.json

在这里插入图片描述

package.json 文件中保存了所接受的默认信息,最后一条是许可证信息:

{
  "name": "first-express-project",
  "version": "1.0.0",
  "description": "express test",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

接下来在 first-express-project 目录中安装 Express,用下面的命令将 Express 保存在 package.json 文件中的依赖表里:

npm install express

此时 package.json 文件的底部会出现依赖列表(“dependencies”),其中包含 Express:

jwdmac2@QideiMac first-express-project % npm i express@next  

added 53 packages, and audited 54 packages in 27s

2 packages are looking for funding
  run `npm fund` for details

3 high severity vulnerabilities

To address issues that do not require attention, run:
  npm audit fix

To address all issues (including breaking changes), run:
  npm audit fix --force

Run `npm audit` for details.
jwdmac2@QideiMac first-express-project % 

@next是安装express的下一个版本 还未发布的版本

package.json 发生变化:

{
  "name": "first-express-project",
  "version": "1.0.0",
  "description": "express test",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^5.0.0-beta.1"
  }
}

卸载包

jwdmac2@QideiMac first-express-project % npm uninstall i express

removed 53 packages, and audited 1 package in 2s

found 0 vulnerabilities

package.json 发生变化:

{
  "name": "first-express-project",
  "version": "1.0.0",
  "description": "express test",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

安装

jwdmac2@QideiMac first-express-project % npm install express

added 58 packages, and audited 59 packages in 17s

8 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

package.json

{
  "name": "first-express-project",
  "version": "1.0.0",
  "description": "express test",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2"
  }
}

如果你已经安装了 Node 和 Express,可以将此代码保存为 app.js,并通过在 bash 中这样运行它:

node ./app.js

app.js

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000, () => {
  console.log('示例应用正在监听 3000 端口 !');
});

前两行通过 require() 导入 Express 模块,并创建了一个 Express 应用。传统上把这个对象命名为 app,它可以进行路由 HTTP 请求、配置中间件、渲染 HTML 视图、注册模板引擎以及修改 应用程序设置 等操作,从而控制应用的行为(例如,环境模式,路由定义是否为区分大小写等)。

代码的中间部分(从 app.get() 开始共三行)是路由定义。app.get() 方法指定了一个回调(callback)函数,该函数在每监听到一个关于站点根目录路径(‘/’)的 HTTP GET 请求时调用。此回调函数以一个请求和一个响应对象作为参数,并直接调用响应的 send() 来返回字符串“Hello World!”

最后一个代码块在“3000”端口上启动服务器,并在控制台打印日志。服务器运行时,可用浏览器访问 localhost:3000,看看响应返回了什么。

失败,未安装 express

node:internal/modules/cjs/loader:1078
  throw err;
  ^

Error: Cannot find module 'express'
Require stack:
- /Users/jwdmac2/Desktop/2023/Vue/app.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1075:15)
    at Module._load (node:internal/modules/cjs/loader:920:27)
    at Module.require (node:internal/modules/cjs/loader:1141:19)
    at require (node:internal/modules/cjs/helpers:110:18)
    at Object.<anonymous> (/Users/jwdmac2/Desktop/2023/Vue/app.js:1:17)
    at Module._compile (node:internal/modules/cjs/loader:1254:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
    at Module.load (node:internal/modules/cjs/loader:1117:32)
    at Module._load (node:internal/modules/cjs/loader:958:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ '/Users/jwdmac2/Desktop/2023/Vue/app.js' ]
}

Node.js v18.16.0

成功

node ./app.js      
示例应用正在监听 3000 端口 !

在浏览器中访问这个 URL(http://127.0.0.1:3000/),如果一切正常,浏览器会直接显示出 “Hello world!” 字符串。
在这里插入图片描述

开发依赖(Development dependencies)

如果一个依赖只在开发过程中用到,应该将其保存为“开发依赖”(这样,包的用户便无需在生产环境中安装它们)。比如,如果要使用 eslint(一款流行的 JavaScript lint 工具)可以这样调用 NPM:

npm install eslint --save-dev

当前应用的 package.json 文件中将自动添加以下项目:

“devDependencies”: {
“eslint”: “^5.12.0”
}

备注: “lint” 是用于对软件进行静态分析的工具,可以发现并报告软件是否遵循某些最佳编程惯例。

https://zh.wikipedia.org/wiki/Lint

运行任务

在 package.json 中,除了定义和获取依赖,还可以定义脚本,然后通过 NPM 的 run-script 命令来运行。这个用法普遍用于自动运行测试单元或部分应用,也可用于构建工具链(比如运行工具来压缩 JavaScript 文件或图片,lint 或分析代码,等等)。

https://docs.npmjs.com/cli/run-script

备注: GulpGrunt 等任务运行器可用于运行测试单元或其他外部工具。

比如,可以在 package.json 文件中添加以下内容来定义一个脚本,从而对上文的代码运行 eslint(假设应用代码在 /src/js 文件夹下):

“scripts”: {

“lint”: “eslint src/js”

}

深入解释一下,eslint src/js 命令可以在终端/命令行对应用目录下的 src/js 目录中的 JavaScript 文件运行 eslint。把上面一段脚本添加进应用的 package.json 中还可以为此命令提供一个快捷方式—— lint。

然后就可以用 NPM 这样运行 eslint 了:

npm run-script lint

或使用别名:

npm run lint

这个示例看上去并没有让原始命令简洁多少,但在 NPM 脚本中可以加入更长的命令,甚至是多命令链。比如可以让单一的 NPM 脚本来一次运行所有的测试单元。

安装 Express 应用生成器

Express 应用生成器 工具可以生成一个 Express 应用的“框架”。可以用 NPM 这样安装它(-g 参数可以把该工具全局安装,那样就可以在任意应用中使用了)

npm install express-generator -g

进入应用目录,运行以下命令,即可创建一个名为 “helloworld” 的 Express 应用:

express helloworld

备注: 也可以指定模板库来使用其他丰富的设置。可通过 help 命令来查看所有选项:express --help

express --help

  Usage: express [options] [dir]

  Options:

        --version        output the version number
    -e, --ejs            add ejs engine support
        --pug            add pug engine support
        --hbs            add handlebars engine support
    -H, --hogan          add hogan.js engine support
    -v, --view <engine>  add view <engine> support (dust|ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
        --no-view        use static html instead of view engine
    -c, --css <engine>   add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
        --git            add .gitignore
    -f, --force          force on non-empty directory
    -h, --help           output usage information
express helloworld

  warning: the default view engine will not be jade in future releases
  warning: use `--view=jade' or `--help' for additional options


   create : helloworld/
   create : helloworld/public/
   create : helloworld/public/javascripts/
   create : helloworld/public/images/
   create : helloworld/public/stylesheets/
   create : helloworld/public/stylesheets/style.css
   create : helloworld/routes/
   create : helloworld/routes/index.js
   create : helloworld/routes/users.js
   create : helloworld/views/
   create : helloworld/views/error.jade
   create : helloworld/views/index.jade
   create : helloworld/views/layout.jade
   create : helloworld/app.js
   create : helloworld/package.json
   create : helloworld/bin/
   create : helloworld/bin/www

   change directory:
     $ cd helloworld

   install dependencies:
     $ npm install

   run the app:
     $ DEBUG=helloworld:* npm start

生成如下文件
在这里插入图片描述

新应用的根目录有一个 package.json 文件。可以打开它看看都安装了哪些依赖,其中可以看到 Express 和 Jade 模板库:

{
  "name": "helloworld",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "cookie-parser": "~1.4.4",
    "debug": "~2.6.9",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "jade": "~1.11.0",
    "morgan": "~1.9.1"
  }
}

用下列命令可为 helloworld 应用安装所有依赖:

cd helloworld
npm install

jwdmac2@QideiMac first-express-project % cd helloworld
jwdmac2@QideiMac helloworld % npm install
npm WARN deprecated constantinople@3.0.2: Please update to at least constantinople 3.1.1
npm WARN deprecated transformers@2.1.0: Deprecated, use jstransformer
npm WARN deprecated jade@1.11.0: Jade has been renamed to pug, please install the latest version of pug instead of jade

added 99 packages, and audited 100 packages in 27s

1 package is looking for funding
  run `npm fund` for details

8 vulnerabilities (1 low, 4 high, 3 critical)

To address all issues (including breaking changes), run:
  npm audit fix --force

Run `npm audit` for details.
jwdmac2@QideiMac helloworld % 

然后运行这个应用(Windows 环境):

SET DEBUG=helloworld:* & npm start

(Linux/macOS 环境):

DEBUG=helloworld:* npm start

直接通过 npm start 命令启动应用也可以,但不会看到调试信息。

DEBUG 命令可以展示应用运行时返回的有用的日志信息,如下所示:

jwdmac2@QideiMac helloworld % DEBUG=helloworld:* npm start

> helloworld@0.0.0 start
> node ./bin/www

  helloworld:server Listening on port 3000 +0ms

打开浏览器并访问 http://127.0.0.1:3000/ 将看到 Express 的默认欢迎页面。

在这里插入图片描述

nodemon

文件改动时只有重启服务器才能看到 Express 网站所做的改动。每次改动后都要手动启停服务器,有必要花点时间让这项工作自动化。

nodemon 是最简便的自动化工具之一。通常将其全局安装(因为它是一个“工具”):

全局安装

npm install -g nodemon # or using yarn: yarn global add nodemon

作为开发依赖将安装在本地

npm install --save-dev nodemon # or using yarn: yarn add nodemon -D
jwdmac2@QideiMac helloworld % sudo npm install -g nodemon

Password:

added 33 packages in 7s

3 packages are looking for funding
  run `npm fund` for details
jwdmac2@QideiMac helloworld % 

如果没有全局安装该工具,就无法从命令行启动它(除非我们将其添加到路径中),但是可以在 NPM 脚本中调用它,因为 NPM 掌握所有已安装包的信息。找到 package.json 的 scripts 部分。在 “start” 一行的末尾添加逗号,并在新的一行中添加 “devstart”,如下所示:

“scripts”: {
“start”: “node ./bin/www”,
“devstart”: “nodemon ./bin/www”
},

现在可以用新建的 devstart 命令启动服务器

这里必须使用“npm run ”命令,而不是 npm start,因为“start”本质上是映射到脚本的一条 NPM 命令。我们可以在 start 脚本中替换它,但我们只想在开发期间使用 nodemon,因此有必要创建一条新的脚本命令。

DEBUG=helloworld:* npm run devstart

jwdmac2@QideiMac helloworld % DEBUG=helloworld:* npm run devstart              

> helloworld@0.0.0 devstart
> nodemon ./bin/www

[nodemon] 2.0.22
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node ./bin/www`
  helloworld:server Listening on port 3000 +0ms

现在,如果编辑项目中的任何文件,服务器将自动重启(或者可以随时使用 rs 命令来重启)。查看更新后的页面需要点击浏览器的“刷新”按钮。

GET / 304 1529.450 ms - -
GET /stylesheets/style.css 304 1.094 ms - -
[nodemon] restarting due to changes...
[nodemon] starting `node ./bin/www`
  helloworld:server Listening on port 3000 +0ms
[nodemon] restarting due to changes...
[nodemon] starting `node ./bin/www`
  helloworld:server Listening on port 3000 +0ms
[nodemon] restarting due to changes...
[nodemon] starting `node ./bin/www`
  helloworld:server Listening on port 3000 +0ms
[nodemon] restarting due to changes...
[nodemon] starting `node ./bin/www`
  helloworld:server Listening on port 3000 +0ms
[nodemon] restarting due to changes...
[nodemon] starting `node ./bin/www`
[nodemon] restarting due to changes...
[nodemon] starting `node ./bin/www`
  helloworld:server Listening on port 3000 +0ms
[nodemon] restarting due to changes...
[nodemon] starting `node ./bin/www`
  helloworld:server Listening on port 3000 +0ms
GET / 200 1527.835 ms - 164
GET /stylesheets/style.css 304 1.234 ms - -

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值