首页 > 解决方案 > 带有不允许字段的 PUT/PATCH 请求

问题描述

我有一个在 Symfony 4 框架中编写的应用程序。我有一个 PUT/PATCH 请求,其中可能包含错误的请求字段。例如 Entity 用户不应包含字段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 框架中做类似的事情?

标签: phpnode.jssymfonyrequestput

解决方案


first, by default when option allow_extra_fieldsis 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 -额外字段

接下来你可以检查是否$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]);

推荐阅读