express入门

144 阅读3分钟

[TOC]

Express

概念

Express是基于Node.js平台,快速、开放、极简的Web开发框架。 理解:Express的作用和Node.js内置的http模块类似,是专门用来创建Web服务器的。

安装

首先假定你已经安装了Node.js,然后执行下面的命令

mkdir myapp
cd myap
npm init
npm install express --save

hello world

首先在工作目录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}`)
})

然后控制台输入命令执行

node app.js

最后浏览器打开 http://localhost:3000/,你就能看到界面上显示“hello world”

Express 应用程序生成器

应用生成器工具express-generator可以快速创建一个应用的骨架。

下面命令创建了一个名称为myapp的Express应用。此应用将创建一个myapp目录,并且设置为使用Pug模板引擎。

npx express-generator --view=pug myapp

安装依赖

cd myapp
npm install

启动项目

set DEBUG=myapp:* & npm start

中间件函数

在Express 中,中间件函数是一个处理 中间件函数可以执行以下操作: 1、执行任何代码 2、修改请求对象和响应对象:中间件函数可以修改请求对象(req)的属性或添加新的属性。这可以用于在后续的中间件函数或路由处理中访问修改后的请求数据。 3、发送响应或调用下一个中间件函数:中间件函数可以发送响应给客户端,也可以调用next()函数将控制权传递给下一个中间件函数或路由处理程序。

可以通过app.use()或者router.use()方法将中间件函数添加到。它们按照添加的顺序依次执行。

应用级中间件app.use

此实例显示了一个没有挂载路径的中间件函数。每次收到请求都会执行该函数

app.use(function (req, res, next) {
  console.log('Time:', Date.now())
  next()
})

此实例显示了一个挂载在/user/:id路径上的中间件函数。当http请求(请求方法不限)路径匹配时,才会执行该函数。

app.use('/user/:id', function (req, res, next) {
  console.log('Request Type:', req.method)
  next()
})

路由级中间件router.use

var express = require('express')
var app = express()
var router = express.Router()


router.use(function (req, res, next) {
  console.log('Time:', Date.now())
  next()
})


router.use('/user/:id', function (req, res, next) {
  console.log('Request URL:', req.originalUrl)
  next()
}, function (req, res, next) {
  console.log('Request Type:', req.method)
  next()
})


router.get('/user/:id', function (req, res, next) {
  // if the user ID is 0, skip to the next router
  if (req.params.id === '0') next('route')
  // otherwise pass control to the next middleware function in this stack
  else next()
}, function (req, res, next) {
  // render a regular page
  res.render('regular')
})


router.get('/user/:id', function (req, res, next) {
  console.log(req.params.id)
  res.render('special')
})

app.use('/', router)

next()和next('route')的区别

1、next(): 当调用next(),它会将控制权传递给下一个中间件函数或者路由处理程序。这意味着它会跳过当前中间件函数的剩余代码,并将请求传递给下一个中间件函数或匹配的路由处理程序。 2、next("route"): 当调用next("route")时,它会跳过当前路由处理程序的剩余代码,并将控制权传递给下一个匹配的路由处理程序。

app.get('/hello', (req, res, next) => {
  console.log('in get 1');
  next()
}, (req, res, next) => {
  console.log('in get 2');
  next('route')  // this will skip the next callback
}, (req, res, next) => {
  console.log('in get 3');
  next()
});

app.get('/hello', (req, res, next) => {
  console.log('in get 4');
});

执行上面代码,控制台会打印为 (in get 3)被跳过了

in get 1
in get 2
in get 4

3、next(!"route"): 当传参的值不是"route"的时候,会将自定义参数param的错误对象传递给错误处理中间件函数。

模板引擎

先安装对应的模板引擎,此处拿pug举例子

npm install pug --save

设置模板文件的目录地址

app.set("views", "./views")
app.set("view engine", 'pug')

创建views目录,在views目录中创建index.pug文件

html
  head
    title= title
  body
    h1= message
app.get('/', function (req, res) {
  res.render('index', { title: 'Hey', message: 'Hello there!' })
})

启动项目,你就会发下index.pug的内容渲染在界面上了。

错误处理中间件

错误处理中间件一般放到文件末尾。 总是需要四个参数,即使你不需要使用next对象,你也必须指定它来维护签名。

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

错误处理