Using Express, can I automatically trim all incoming POSTed fields in req.body?

拥有回忆 提交于 2019-12-11 12:09:48

问题


I started by using express-form with my api (Express 3.3.8) in order to trim leading and trailing whitespace off of incoming POSTed fields.

However, I believe to use it I must include the form fields and rules in my middleware to my routes like so:

app.post('/api/test', form( field("username").trim(), field("password").trim(), function(req, res...

My question is, is there a way to do the trim automatically without specifying the fields individually? I know of the configuration option: autoTrim, but I think I still need to specify the fields on a per route/middleware basis, right? I tried leaving it out of the middleware, and just doing the form.configure({autoTrim:true}), but nothing changed with the req.body fields. Same as if I never included express-form at all.

I'm not committed to express-form. If there's another way already available to have Express always trim incoming req.body fields, please let me know.


回答1:


As it seems one must declare the fields individually using express-form, I decided to write my own whitespace trimming middleware for now as I couldn't find an existing simple solution. I use underscore.js, so you'll see its map function in use. You could otherwise do your own looping with the native Object.keys or similar. This completely rewrites all fields in req.body! Please note, this is a stop-gap for a greater validation issue. We're just doing this temporarily until we have time to clean up validation as a whole. Here's my code (put before app.use(app.router) of course):

var trimmer = function(req, res, next){
  req.body = _.object(_.map(req.body, function (value, key) {
    return [key, value.trim()];
  }));
  next();
}

app.use(trimmer);



回答2:


app.use(postTrimmer);

function postTrimmer(req, res, next) {
    if (req.method === 'POST') {
        for (const [key, value] of Object.entries(req.body)) {
            req.body[key] = value.trim();
        }
    }
    next();
}

Don't forget to turn on the "body-parser" module before using postTrimmer middleware.



来源:https://stackoverflow.com/questions/30266295/using-express-can-i-automatically-trim-all-incoming-posted-fields-in-req-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!