最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

I've implemented express-validator and am trying to sanitize an input field where users are searching a particular query.

The test query I'm using is <script>Malicious code</script. As the request es in, I use:

req.sanitizeQuery('searchQuery');

When I then check to see if the query has been sanitized, the string hasn't been altered/sanitized in any way.

I could be fundamentally misunderstanding sanitization here, in which case please point it out. If I am, then I can go and fill in my gaps on knowledge, but in the meantime, what "test" query can I throw at my sanitizer to check that it's working?

I've implemented express-validator and am trying to sanitize an input field where users are searching a particular query.

The test query I'm using is <script>Malicious code</script. As the request es in, I use:

req.sanitizeQuery('searchQuery');

When I then check to see if the query has been sanitized, the string hasn't been altered/sanitized in any way.

I could be fundamentally misunderstanding sanitization here, in which case please point it out. If I am, then I can go and fill in my gaps on knowledge, but in the meantime, what "test" query can I throw at my sanitizer to check that it's working?

Share Improve this question asked Mar 13, 2018 at 9:58 ModermoModermo 1,9922 gold badges31 silver badges48 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

Looking at the documentation, express-validator is meant to be used as middleware.

So I would say you want some code that looks a bit like this:

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);
});

We're using the sanitizeQuery function as middleware which is going to sanitise the value req.query.searchQuery. I'm assuming since it's a sanitisation function, it will not trigger any errors ing from validationResult, instead it will return a clean response for you.

You should then be able to request your service at your {{host}}/search?searchQuery= <script>Malicious code</script> where {{host}} is your services host such as http://localhost:8080.

发布评论

评论列表(0)

  1. 暂无评论