查看文档,express-validator旨在用作中间件。
所以我会说你想要一些看起来有点像这样的代码:
const { validationResult } = require('express-validator/check');
const { sanitizeQuery } = require('express-validator/filter');
// Setup the request handler, give it some validation middleware
// then the main request handler
app.get('/search', [sanitizeQuery('searchQuery').escape()], function(req, res, next) {
// Deal with any errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.mapped() });
}
// req.query.searchQuery was sanitised via the middleware, it should now
// be clean.
console.log(req.query.searchQuery);
});
我们使用 sanitizeQuery 函数作为中间件来清理 value req.query.searchQuery
。我假设因为它是一个清理功能,它不会触发来自validationResult的任何错误,而是会为您返回一个干净的响应。
然后,您应该能够在您的服务主机{{host}}/search?searchQuery= <script>Malicious code</script>
所在的位置请求您的服务,{{host}}
例如http://localhost:8080
.