【问题标题】:Express - Validation for Patch RequestsExpress - 验证补丁请求
【发布时间】:2021-07-10 18:27:02
【问题描述】:

我是一名前端开发人员,尝试使用 Node/Express 为我的项目创建其余 api。

我使用Joi 进行验证。我很好奇我如何PATCH 请求路由。我不能使用Joi,因为它说this field is required

所以我想知道如何验证PATCH 请求路由。因为我不知道我会得到什么数据。未经验证使用req.body 会出现什么问题?

export const updateAccount = asyncHandler(async (req, res) => {
  let values = req.body;

  if (req.method === 'PUT') {
    values = await accountSchema.validateAsync(req.body);
  }

  const account = await Account.findByIdAndUpdate(req.params.id, values, {
    new: true,
  });

  if (!account) {
    return res.status(404).json({ message: 'Account not found' });
  }

  res.status(200).json(account);
});

【问题讨论】:

  • 没有在邮递员之外花任何时间使用 joi,但这里有一个示例,说明如何使用 express 验证器 github.com/alilland/nodejs-api/blob/master/src/routes/…
  • 来自其他语言的nodejs,如果可以的话,验证收到的每个值非常重要,否则你只是在自找麻烦。但是,您会发现大多数新的 javascript 开发人员和许多撰写博客文章的人都不会验证他们的有效负载,这很危险。软件开发人员最关心的问题就在这里,owasp.org/www-project-top-ten 和 XSS 攻击是您试图通过验证字段来避免的。
  • 谢谢!看起来我必须为补丁请求创建另一个模式来验证用户输入,而不是在没有验证的情况下使用 req.body

标签: node.js express joi


【解决方案1】:

正如@aliland 提到的,并且也遵循永远不要相信用户输入。我为补丁请求创建了一个新的Joi 架构。因为对于当前架构,它抱怨必填字段。

我的架构:

const accountSchemaForPatchRequests = Joi.object({
  firstName: Joi.string().min(3).max(30),
  lastName: Joi.string(),
  email: Joi.string().email(),
  password: Joi.string().min(8),
});

和控制器:

export const updateAccount = asyncHandler(async (req, res) => {
  let values = req.body;

  if (req.method === 'PUT') {
    values = await accountSchema.validateAsync(req.body);
  } else {
    values = await accountSchemaForPatchRequests.validateAsync(req.body);
  }

  const account = await Account.findByIdAndUpdate(req.params.id, values, {
    new: true,
  });

  if (!account) {
    return res.status(404).json({ message: 'Account not found' });
  }

  res.status(200).json(account);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    • 2014-04-20
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    相关资源
    最近更新 更多