前言
在使用 Hapi 进行 Web 开发时,我们通常需要对请求参数进行校验。请求参数校验可以有效地防止恶意请求和错误数据的问题。本文将介绍如何在 Hapi 中实现请求参数校验。
Hapi 的 Joi 模块
Hapi 提供了一个叫做 Joi 的模块,可以用于参数校验。Joi 是一个强大的校验库,拥有广泛的校验类型和自定义校验规则的能力,而且易于使用和配置。
在使用 Joi 之前,需要先安装和引入:
npm install @hapi/joi
const Joi = require('@hapi/joi');
基本使用方式
单个参数的校验
假设我们要校验一个名为 name
的参数是不是字符串类型,且最大长度为 10。可以使用 Joi 的 string()
和 max()
方法进行校验:
const schema = Joi.object({ name: Joi.string().max(10).required(), }); const result = schema.validate({ name: 'myName' }); console.log(result); // Output: { value: { name: 'myName' }, error: undefined }
如果 name
参数的值为无效值或过长,将会出现错误:
const result = schema.validate({ name: 'myLongName' }); console.log(result); // Output: { value: { name: 'myLongName' }, error: [ValidationError: "name" length must be less than or equal to 10 characters long] }
多个参数的校验
在校验多个参数时,可以把多个参数结合在一个 Joi 对象中,并使用 keys()
方法指定每个参数的校验规则:
const schema = Joi.object({ name: Joi.string().max(10).required(), age: Joi.number().min(18).max(99).required(), }); const result = schema.validate({ name: 'myName', age: 20 }); console.log(result); // Output: { value: { name: 'myName', age: 20 }, error: undefined }
URL 参数校验
在 Hapi 中,可以使用 request.params
来获取 URL 参数,使用 Joi 对这些参数进行校验:
-- -------------------- ---- ------- ----- ------ - ------------ ----- -------------------------------- --- -------------- ------- ------ ----- ---------- -------- -------- --------- -- - ----- ------ - -------------------------------- -- -------------- - ------ ------------------------------------------------------ - ---- - ------ ------- - - ------------------- - ---- - - ---展开代码
在浏览器中访问 http://localhost:8000/myLongName
将会出现错误提示:
"name" length must be less than or equal to 10 characters long
请求体参数校验
在 Hapi 中,使用 request.payload
来获取请求体参数。与 URL 参数一样,可以使用 Joi 对请求体参数进行校验:
-- -------------------- ---- ------- ----- ------ - ------------ ----- -------------------------------- --- -------------- ------- ------- ----- -------- -------- -------- --------- -- - ----- ------ - --------------------------------- -- -------------- - ------ ------------------------------------------------------ - ---- - ------ ------- - - -------------------- - ---- - - ---展开代码
在发送如下请求时,将出现错误提示:
POST /user HTTP/1.1 Host: localhost:8000 Content-Type: application/json { "name": "myLongName" }
自定义校验规则
Joi 提供了一些内置的校验规则,但我们也可以自定义校验规则。自定义规则可以让我们更加灵活地进行校验。
使用 Joi.function()
方法可以自定义一个函数作为校验规则。下面是一个自定义校验规则的示例,该规则用于验证一个字符串中是否包含数字:
const schema = Joi.object({ name: Joi.string().max(10).required(), password: Joi.string().pattern(/[0-9]/), }); const result = schema.validate({ name: 'myName', password: 'mypassword' }); console.log(result); // Output: { value: { name: 'myName', password: 'mypassword' }, error: [ValidationError: "password" with value "mypassword" fails to match the required pattern: /[0-9]/] }
本文介绍了在 Hapi 中如何使用 Joi 实现请求参数校验,包括单个参数的校验、多个参数的校验、URL 参数的校验和请求体参数的校验,以及如何自定义校验规则。通过使用 Joi 进行请求参数校验,可以有效避免恶意请求和错误数据的问题。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67c11e1b314edc26848a2479