V.A*_*yan 17 javascript sanitization 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);
}
Run Code Online (Sandbox Code Playgroud)
kga*_*har 10
您可以使用sanitize节点模块:
npm install sanitize --save
Run Code Online (Sandbox Code Playgroud)
然后可以使用像:
var sanitizer = require('sanitize')();
var name = sanitizer.value(req.name, 'string');
var surname= sanitizer.value(req.surname, 'string');
Run Code Online (Sandbox Code Playgroud)
有更多可以通过清理文档
如果您不想使用任何第三方模块并希望使用内置节点进行清理.你可以试试以下:
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
})
Run Code Online (Sandbox Code Playgroud)
其实,我写了一个包来轻松解决这个问题。你可以使用它或在 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15483 次 |
| 最近记录: |