【问题标题】:PUT/PATCH request with not allowed fields带有不允许字段的 PUT/PATCH 请求
【发布时间】:2019-07-01 11:18:43
【问题描述】:

我有一个使用 Symfony 4 框架编写的应用程序。我有一个 PUT/PATCH 请求,其中可能包含错误的请求字段。例如,实体用户不应包含字段 description。在这种情况下,我想阻止请求并返回错误的请求响应。我想知道在 Symfony 4 中最好的方法是什么?

In node.js implenentation such problem looks like below: 

router.patch('/tasks/:id', async (req, res) => {
    const updates = Object.keys(req.body)
    // allowed fields
    const allowedUpdates = ['description', 'completed']
    // check if there are bad fields
    const isValidOperation = updates.every((update) => allowedUpdates.includes(update))
    if (!isValidOperation) {
        return res.status(400).send({ error: 'Invalid updates!' })
    }
    /*
    some response code
    /*
})

如何在 Symfony 4 框架中做类似的事情?

【问题讨论】:

  • 请不要使用不相关的标签进行标记,因此您会被 sb 否决,这个问题与节点 js 无关,所以不要这样标记。

标签: php node.js symfony request put


【解决方案1】:

first, by default when option allow_extra_fields is set to false (default), form with extra fields would not validate, more about this setting: https://symfony.com/doc/current/reference/forms/types/form.html#allow-extra-fields

接下来你可以检查$form->getExtraData()是否是一个空数组,这意味着没有额外的字段

如果发现额外的字段会导致错误的请求响应,您可以:

throw new BadRequestHttpException();

或无一例外:

return $this->json(['error' => 'your error'], Response::HTTP_BAD_REQUEST);

return new JsonResponse(['error' => 'your error', Response::HTTP_BAD_REQUEST]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 2015-06-18
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    相关资源
    最近更新 更多