php - 带有不允许字段的 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 框架中做类似的事情?
解决方案
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 -额外字段
接下来你可以检查是否$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]);
推荐阅读
- node.js - amqp.connect 无法永久保持连接
- r - 从列表中提取单个图
- oracle - 如何在 Oracle Commerce Cloud 中更新上传小部件的新版本?
- c# - Cannot use SendGrid
- vba - Yahoo Finance Cookie Crumb no longer working
- css - 使用Angular动态生成具有固定宽度列的表格
- c# - Adding newline to byte sequence when writing to filestream
- c# - LINQ: latest sum of data within data range
- javascript - UIslider buttons doesn't work with checkbox filter
- sql - SubCount Divided By Total Count