我怎么知道我的输入正在被 express-validator 清理?

How do I know my input is being sanitized by express-validator?

我已经实施 express-validator 并正在尝试清理用户搜索特定查询的输入字段。

我使用的测试查询是 <script>Malicious code</script。随着请求的到来,我使用:

req.sanitizeQuery('searchQuery');

然后当我检查查询是否已被清理时,该字符串没有以任何方式 altered/sanitized。

我可能从根本上误解了这里的消毒,在这种情况下请指出。如果是,那么我可以去填补我的知识空白,但与此同时,我可以向我的消毒剂提出什么 "test" 查询来检查它是否有效?

查看文档,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 函数作为中间件,它将清理值 req.query.searchQuery。我假设因为它是一个清理功能,它不会触发来自 validationResult 的任何错误,而是 return 为您提供一个干净的响应。

然后您应该能够在您的 {{host}}/search?searchQuery= <script>Malicious code</script> 请求您的服务,其中 {{host}} 是您的服务主机,例如 http://localhost:8080.