首页 > 其他分享 >express框架学习笔记

express框架学习笔记

时间:2022-11-13 17:12:13浏览次数:43  
标签:function express 框架 res app req 中间件 笔记 next

前言

前几天军训 然后利用晚上时间学习了一下express 然后想看几道node的题题目 感觉看的代码很混乱 看不太透彻 打算这次通过记笔记的方法来学习一下 express

还是跟着官方文档学习吧

正文

基本路由

路由时确定应用程序如何响应客户端对特定端点的请求,该端点时url(或路径)和特定的http请求方法(get,post)每个路由有一个或者多个处理函数,当路由匹配时执行处理函数。

路由定义采用一下结构

app.METHOD(PATH,HANDLER)

app是一个express的示例

METHOD是一个http请求方法,小写

path是服务器上的路径。

HANDLER 是路由匹配时执行的函数

以下示例说明了定义简单路由

hello world在‘/’下回复

const express=require('express');
const app=express();
const port=3000
app.get('/',(req,res)=>{
    res.send('hello word');
})
app.listen(port,()=>{
    console.log('on 3000');
})

post请求

const express=require('express');
const app=express();
const port=3000
app.post('/',(req,res)=>{
    res.send('hello word');
})
app.listen(port,()=>{
    console.log('on 3000');
})

app.all()是处理所有http请求方法

使用app.use()将中间件指定为回调函数

路由参数

路由参数是命名的URL段,用于捕获在URL中的指定的值。捕获的值填充到req.params 对象中,路径中指定的路由参数的名称作为他们各自的键。

	Route.path:/users/:userid/bookd/:bookid
	Request URL: http://localhost:3000/users/34/books/8989
	req.params: { "userId": "34", "bookId": "8989" }

实例

要使用路由参数定义路由,只需要在路由的路径中指定路由参数

const express=require('express');
const app=express();
const port=3000
app.get('/users/:userId/books/:bookId',(req,res)=>{
    res.send(req.params);
})
app.listen(port,()=>{
    console.log('on 3000');
})

路由参数的名称必须由“单词字符”([A-Za-z0-9_])组成。

路由处理程序

可以提供多个回调函数,他们的行为类似于中间件来处理请求。唯一的例外是这些回调函数可能会调用next('route')一绕过剩余路由的回调

单个回调函数处理路由

app.get('/example/a', function (req, res) {
    res.send('Hello from A!')
})

一个以上的回调函数可以处理一个路由(确保你指定了next对象)。例如:

app.get('/example/b', function (req, res, next) {
    console.log('the response will be sent by the next function ...')
    next()
}, function (req, res) {
    res.send('Hello from B!')
})

一组回调函数可以处理路由。例如:

var cb0 = function (req, res, next) {
  console.log('CB0')
  next()
}

var cb1 = function (req, res, next) {
  console.log('CB1')
  next()
}

var cb2 = function (req, res) {
  res.send('Hello from C!')
}

app.get('/example/c', [cb0, cb1, cb2])

独立函数和函数数组的组合可以处理路由。例如:

var cb0 = function (req, res, next) {
  console.log('CB0')
  next()
}

var cb1 = function (req, res, next) {
  console.log('CB1')
  next()
}

app.get('/example/d', [cb0, cb1], function (req, res, next) {
  console.log('the response will be sent by the next function ...')
  next()
}, function (req, res) {
  res.send('Hello from D!')
})

响应方法

image-20221113153047694

中间件

这些东西打算以后遇到的中有的话 具体的去学

编写用于express应用程序的中间件

中间件函数可以访问请求对象(req)响应对象(res)和next应用程序请求

next函数是 Express 路由器中的一个函数,当被调用时,它会在当前中间件之后执行中间件。

中间件函数 myLogger

这是一个名为“myLogger”的中间件函数的简单示例,对当应用程序的请求通过它是,此函数只会打印“LOGGED”.中间件函数被分配给一个名为myLogger的变量

var myLogger = function (req, res, next) {
  console.log('LOGGED')
  next()
}

注意上面对 的调用next()。调用此函数会调用应用程序中的下一个中间件函数。该next()函数不是 Node.js 或 Express API 的一部分,而是传递给中间件函数的第三个参数。该next()函数可以命名为任何名称,但按照惯例,它始终命名为“next”。为避免混淆,请始终使用此约定。

要加载中间件函数,调用app.use()指定中间件函数,例如以下代码myLooger在路由到根路径(/)之前加载中间件函数

var express = require('express')
var app = express()

var myLogger = function (req, res, next) {
  console.log('LOGGED')
  next()
}

app.use(myLogger)

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

app.listen(3000)

每次应用程序收到请求时,它都会将消息“LOGGED”打印到终端。

中间件函数加载的顺序很重要 首先加载的中间件函数也会先执行

中间件函数 requestTime

接下来,我们将创建一个名为“requestTime”的中间件函数

var requestTime = function (req, res, next) {
  req.requestTime = Date.now()
  next()
}

应用级中间件

var express = require('express')
var app = express()

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

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

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

此示例显示了安装在/user/:id路径上的中间件函数。该函数针对/user/:id路径上的任何类型的 HTTP 请求执行。

app.get('/user/:id', function (req, res, next) {
  res.send('USER')
})

这个例子展示了一个路由和它的处理函数(中间件系统)。/user/:id该函数处理对路径的 GET 请求。

路由器级中间件

路由器级中间件的工作方式与应用级中间件相同,只是它绑定到express.Router().

var router = express.Router()

route.use()使用和router.METHOD() 函数加载路由器级中间件。

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

// a middleware function with no mount path. This code is executed for every request to the router
router.use(function (req, res, next) {
  console.log('Time:', Date.now())
  next()
})

// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
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()
})

// a middleware sub-stack that handles GET requests to the /user/:id path
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')
})

// handler for the /user/:id path, which renders a special page
router.get('/user/:id', function (req, res, next) {
  console.log(req.params.id)
  res.render('special')
})

// mount the router on the app
app.use('/', router)

错误处理中间件

错误处理中间件总是需要四个参数。您必须提供四个参数以将其标识为错误处理中间件函数。即使您不需要使用该next对象,您也必须指定它来维护签名。否则,该next对象将被解释为常规中间件并且无法处理错误。

以与其他中间件函数相同的方式定义错误处理中间件函数,除了使用四个参数而不是三个参数,特别是使用签名(err, req, res, next)):

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

第三方中间件

题目中遇到的话 再学吧

在 Express 中使用模板引擎

模板引擎可以使咋子应用程序设计中使用静态模板文件。在运行时,模板引擎将模板文件中的变量替换为实际值,并将模板转换为发送给客户端的HTML文件。这种设计方法使设计HTML页面变得更加容易。

要呈现模板文件,请设置以下[应用程序设置属性,在app.js生成器创建的默认应用程序中设置:

views 模板文件所在目录。例如:

app.set('view','./views')

这默认为views应用程序根目录中的目录。

view engine 要使用的模板引擎。例如要使用Pug模板引擎:app.set('view engine','pug')

然后安装对应的模板引擎npm包

npm install pug --save

设置好视图引擎后,您无需在应用中指定引擎或加载模板引擎模块;Express 在内部加载模块,如下所示(对于上面的示例)。

app.set('view engine', 'pug')

在views目录下创建一个index.pug模板文件

内容如下

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

错误处理

错误处理是指Express如何捕获和处理同步和异步发生的错误。express带有一个默认的错误处理程序,因此您无需编写自己的程序即可开始使用

捕获错误

确保Express捕获运行路由处理程序和中间件时发生的错误非常重要

。。。先看会题吧

标签:function,express,框架,res,app,req,中间件,笔记,next
From: https://www.cnblogs.com/kkkkl/p/16886315.html

相关文章