使用Express,我可以自动修剪req.body中所有传入的POST字段吗? [英] Using Express, can I automatically trim all incoming POSTed fields in req.body?
问题描述
我首先将api(Express 3.3.8)与 express-form 一起使用修剪掉传入的POST字段中的前导和尾随空格.
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...
app.post('/api/test', form(
field("username").trim(),
field("password").trim(), function(req, res...
我的问题是,有没有一种方法可以自动进行修剪而无需单独指定字段?我知道配置选项:autoTrim
,但是我仍然需要基于每个路由/中间件指定字段,对吗?我尝试将其保留在中间件之外,仅执行form.configure({autoTrim:true})
,但对req.body
字段没有任何更改.就像我根本不包含express-form
一样.
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.
我不致力于express-form
.如果还有其他方法可以让Express始终修剪传入的req.body
字段,请告诉我.
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.
推荐答案
似乎必须使用express-form
分别声明字段,所以我决定现在编写自己的空白修剪中间件,因为我找不到现有的中间件简单的解决方案.我使用的是underscore.js
,因此您会看到其使用中的map
功能.否则,您可以使用本机Object.keys
或类似的代码进行自己的循环.这将完全重写req.body
中的所有字段!请注意,这是更大的验证问题的权宜之计.我们只是暂时执行此操作,直到有时间清理整个验证为止.这是我的代码(当然要放在app.use(app.router)
之前):
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);
这篇关于使用Express,我可以自动修剪req.body中所有传入的POST字段吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!