Javascript 如何清理节点 js 中的输入值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46718772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:35:00  来源:igfitidea点击:

How I can sanitize my input values in node js?

javascriptnode.jssanitization

提问by V.Aleksanyan

I validated my Node.js inputs so that they won't be empty, but I want sanitize them too. Please help me how I can do this.

我验证了我的 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);
}

回答by kgangadhar

  • For most of the framework, you can use sanitizenode module:

    npm install sanitize --save
    

    And then can use like:

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

    For more can go through sanitizedocumentation

  • If you are using express, then you can validate and sanitize using built-in express functionalities as follows:

    const express = require('express')
    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
    })  
    

    For more can go through express-validatorand express-sanitize-inputdocumentation.

  • If you are using Hapi, then you can validate and sanitize using Joi, With the Joi you can sanitize variable with addition options

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

    For more can go through Joidocumentation.

  • If you don't want to use any third party module and want to sanitize using the build-in node. you can try following:

    // 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 !== null ? obj : {};
    
  • 对于大多数框架,您可以使用sanitizenode 模块:

    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 功能进行验证和清理,如下所示:

    const express = require('express')
    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 !== null ? obj : {};
    

回答by Md Fazlul Karim

Actually, I wrote a package to solve this problem easily. You can use it or contribute to it on Github.

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

Download this package from here: https://www.npmjs.com/package/string-sanitizer

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

You can use this utility package to sanitize even foreign languages other than English. Under the hood, regex is used in this library. You can convert your string to URL or filename friendly string. The use cases are given below

您甚至可以使用此实用程序包来清理除英语之外的外语。在幕后,这个库中使用了正则表达式。您可以将字符串转换为 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

Codeblock

代码块

enter image description here

在此处输入图片说明