繁体   English   中英

如何清理 node.js 中的输入值?

[英]How I can sanitize my input values in node js?

我验证了我的 Node.js 输入,这样它们就不会为空,但我也想清理它们。 请帮助我如何做到这一点。

req.checkBody('name', 'Name is required!').notEmpty();
req.checkBody('surname', 'Surname is required!').notEmpty();
req.checkBody('username', 'Username is required!').notEmpty();
req.checkBody('password', 'Password is required!').notEmpty();
req.checkBody('password2', 'Passwords do not match!').equals(req.body.password);

var errors = req.validationErrors();

if (errors) {
    res.render('user/register', {
        errors: errors,
        user: null,
        title: 'Register'
    });
}
else {
    var userData = {
        name : req.body.name,
        surname : req.body.surname,
        username : req.body.username,
        password : req.body.password,
        avatar : 'No_person.jpg'
    };
    userController.addUser(req,res,userData);
}
  • 对于大多数框架,您可以使用sanitize node 模块:

     npm install sanitize --save

    然后可以使用像:

     var sanitizer = require('sanitize')(); var name = sanitizer.value(req.name, 'string'); var surname= sanitizer.value(req.surname, 'string');

    有关更多信息,请参阅 sanitize文档

  • 如果您使用express ,那么您可以使用express-validatorexpress-sanitize-input进行验证清理,如下所示:

     const express = require('express'); const { check } = require('express-validator'); const app = express(); app.use(express.json()) app.post('/form', [ check('name').isLength({ min: 3 }).trim().escape(), check('email').isEmail().normalizeEmail(), check('age').isNumeric().trim().escape() ], (req, res) => { const name = req.body.name const email = req.body.email const age = req.body.age })

    如需更多信息,请参阅express-validatorexpress-sanitize-input文档。

  • 如果您正在使用Hapi ,那么您可以使用Joi进行验证和清理,使用 Joi,您可以使用其他选项清理变量

     validate(value, schema, {escapeHtml: true}, [callback])

    更多内容可以查看Joi文档。

  • 如果您不想使用任何第三方模块并希望使用内置节点进行清理。 您可以尝试以下操作:

     // For string variables str = typeof(str) === 'string' && str.trim().length > 0 ? str.trim() : ''; // for boolean values bool = typeof(bool) === 'boolean' && bool === true ? true : false; // for array values arr = typeof(arr) === 'object' && arr instanceof Array ? arr : []; // for number values num = typeof(num) === 'number' && num % 1 === 0 ? num : 0; // for objects obj = typeof(obj) === 'object' && !(obj instanceof Array) && obj !== null ? obj : {};

其实,我写了一个包来轻松解决这个问题。 你可以使用它或在 Github 上贡献它。

从这里下载这个包: https : //www.npmjs.com/package/string-sanitizer

您甚至可以使用此实用程序包来清理除英语之外的外语。 在幕后,这个库中使用了正则表达式。 您可以将字符串转换为 URL 或文件名友好字符串。 用例如下

var string = require("string-sanitizer");

string.sanitize("a.bc@d efg#h"); // abcdefgh
string.sanitize.keepSpace("a.bc@d efg#h"); // abcd efgh
string.sanitize.keepUnicode("a.bc@d efg#hক"); // abcd efghক
string.sanitize.addFullstop("a.bc@d efg#h"); // abcd.efgh
string.sanitize.addUnderscore("a.bc@d efg#h"); // abcd_efgh
string.sanitize.addDash("a.bc@d efg#h"); // abcd-efgh
string.sanitize.removeNumber("@abcd efgh123"); // abcdefgh
string.sanitize.keepNumber("@abcd efgh123"); // abcdefgh123
string.addFullstop("abcd efgh"); // abcd.efgh
string.addUnderscore("@abcd efgh"); // @abcd_efgh
string.addDash("@abcd efgh"); // @abcd-efgh
string.removeSpace("@abcd efgh"); // @abcdefgh

代码块

在此处输入图片说明

validator每周有 500 万次下载,似乎是当今业界最受欢迎的软件包。 express-validator使用validator作为它的核心。 这些当然是一种选择,其他软件包如xsssanitize-html

关于两个验证器包都有大量文档,这里是关于消毒的部分:

https://express-validator.github.io/docs/sanitization.html

我使用 Yup 进行验证。 package 比 Joi 小很多。 我在前端和后端都使用了 Yup,我通常将验证放入共享的 npm package 前端和后端项目都可以具有相同的验证库

npm install -S yup

然后

import * as yup from 'yup';

let schema = yup.object().shape({
  name: yup.string().required(),
  age: yup.number().required().positive().integer(),
  email: yup.string().email(),
  website: yup.string().url(),
  createdOn: yup.date().default(function () {
    return new Date();
  }),
});

// check validity
schema
  .isValid({
    name: 'jimmy',
    age: 24,
  })
  .then(function (valid) {
    valid; // => true
  });

来自 Yup 的网站:

Yup 是一个用于值解析和验证的 JavaScript 架构构建器。 定义模式、转换值以匹配、验证现有值的形状,或两者兼而有之。 Yup 模式具有极强的表现力,允许对复杂的、相互依赖的验证或值转换进行建模。

Yup 的 API 深受 Joi 的启发,但更精简并且以客户端验证作为其主要用例构建。 是的,将解析和验证函数分成不同的步骤。 cast() 转换数据,而 validate 检查输入的形状是否正确。 每个都可以一起执行(例如 HTML 表单验证)或单独执行(例如从 API 反序列化可信数据)。

您将希望为密码匹配等特殊项目创建自己的验证器。这可以使用正则表达式完成,然后将 function 添加到 Yup,如下所示:

let schema = string().matches(/(hi|bye)/);

将您所有的验证函数放入您共享的 NPM package(包括您的 typescript 类型等)。 您的前端团队与后端验证不同步的情况现在不再需要担心。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM