【Node.js】Node.js入门(三):Express安装、测试、使用

1、简述

Express是基于 Node.js 平台,快速、开放、极简的 Web 开发框架。官网地址如下:

https://www.expressjs.com.cn/

Nodejs和Express的区别
Nodejs本身其实只提供了文件、网络端口监听、字符集等基本的操作。
Express提供了BS架构服务端的基本框架,比如路由功能、异常处理等等。
Express.js是一个基于Node.js的框架,用于使用Node.js的原理和方法开发Web应用程序。

2、安装步骤

2.1 安装环境

系统环境:ubuntu18.04
依赖包:先安装Node.js,参考【Node.js】Node.js入门(一):安装、编辑、编译运行

2.2 安装Express

创建目录:

$ mkdir mypp
$ cd myqpp

创建 package.json 文件

$ npm init

一路回车即可
下载保存Express包

$ npm install express --save

2.3 查看安装的模块

安装完毕,是不是想看看都安装了哪些模块、文件,它们都在当前目录node_modules下,使用tree命令查看:

myapp$ tree -L 2
.
├── node_modules
│   ├── accepts
│   ├── array-flatten
│   ├── body-parser
│   ├── bytes
│   ├── call-bind
│   ├── content-disposition
│   ├── content-type
│   ├── cookie
│   ├── cookie-signature
│   ├── debug
│   ├── depd
│   ├── destroy
│   ├── ee-first
│   ├── encodeurl
│   ├── escape-html
│   ├── etag
│   ├── express
│   ├── finalhandler
│   ├── forwarded
│   ├── fresh
│   ├── function-bind
│   ├── get-intrinsic
│   ├── has
│   ├── has-symbols
│   ├── http-errors
│   ├── iconv-lite
│   ├── inherits
│   ├── ipaddr.js
│   ├── media-typer
│   ├── merge-descriptors
│   ├── methods
│   ├── mime
│   ├── mime-db
│   ├── mime-types
│   ├── ms
│   ├── negotiator
│   ├── object-inspect
│   ├── on-finished
│   ├── parseurl
│   ├── path-to-regexp
│   ├── proxy-addr
│   ├── qs
│   ├── range-parser
│   ├── raw-body
│   ├── safe-buffer
│   ├── safer-buffer
│   ├── send
│   ├── serve-static
│   ├── setprototypeof
│   ├── side-channel
│   ├── statuses
│   ├── toidentifier
│   ├── type-is
│   ├── unpipe
│   ├── utils-merge
│   └── vary
├── package.json
└── package-lock.json

57 directories, 2 files

3、Hello World测试

创建Hello World web服务器,在浏览器页面中打印出:Hello World。只需简单的三步:

3.1 创建app.js

在myapp目录中创建app.js文件,内容如下

const express = require('express')
const app = express()
const port = 3000

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

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

3.2 运行

$ node app.js

3.3 测试

在浏览器中输入 http://localhost:3000/,将会看到打印输出“Hello World!”

4、使用Express创建应用骨架

4.1 创建应用骨架

创建目录

$ mkdir generator

进入目录

$ cd generator

生成应用目录结构

$ npx express-generator

输出打印信息:

$ npx express-generator
Need to install the following packages:
  express-generator@4.16.1
Ok to proceed? (y) y
npm WARN deprecated mkdirp@0.5.1: Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)

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


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

   install dependencies:
     $ npm install

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

4.2 安装依赖包

使用npm命令安装所有依赖包

$ npm install

输出打印信息:

npm WARN deprecated transformers@2.1.0: Deprecated, use jstransformer
npm WARN deprecated constantinople@3.0.2: Please update to at least constantinople 3.1.1
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 10s

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

5 vulnerabilities (1 low, 4 critical)

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

Run `npm audit` for details.

4.3 运行

$ DEBUG=generator:* npm start

输出打印信息:

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

  generator:server Listening on port 3000 +0ms

4.4 测试

在浏览器中输入:http://localhost:3000/,可见如下信息

Express
Welcome to Express

5 基本路由

路由使用方法

app.METHOD(PATH, HANDLER)

参数说明:

app 是express的实例化:var app = express();
METHOD是HTTP方法,GET,、POST、PUT、DELETE
PATH是相对服务的路径
HANDLER是个函数,执行相应的路由请求

常用路由举例

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

app.post('/', function (req, res) {
  res.send('Got a POST request')
})

app.put('/user', function (req, res) {
  res.send('Got a PUT request at /user')
})

app.delete('/user', function (req, res) {
  res.send('Got a DELETE request at /user')
})

6、静态文件浏览

想要查看图像、CSS 文件或者 JavaScript 文件之类的静态文件,推荐使用 Express 中的 express.static 内置中间件函数。

express.static(root, [options])

示例一:

app.use(express.static('public'))

现在,可以访问 public 目录中的所有文件了:

http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html

示例二

app.use('/static', express.static('public'))

现在,可以通过带有 /static 前缀地址来访问 public 目录中的文件了。

http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html

示例三:
上面都是相对路径,相对于执行程序的路径,下面的方法可以使用绝对路经,推荐使用这个方法,比较安全

const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'public')))
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

郭老二

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值