Symfony FOSRestBundle POST请求500错误

时间:2015-05-01 09:21:26

标签: php symfony fosrestbundle

我尝试使用FOSRestBundle创建实体。

网址:

POST http://localhost:8000/app_dev.php/api/links

请求有效负载:

{"link":{"id":"5","title":"foo","description":"foo","url":"foo","image":null,"issue":"1","creator":"1"}
}

这是控制器(生成):

/**
 * Create a Link entity.
 *
 * @View(statusCode=201, serializerEnableMaxDepthChecks=true)
 *
 * @param Request $request
 *
 * @return Response
 *
 */
public function postAction(Request $request)
{
    $entity = new Link();
    $form = $this->createForm(new LinkType(), $entity, array("method" => $request->getMethod()));
    $this->removeExtraFields($request, $form);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();

        return $entity;
    }

    return FOSView::create(array('errors' => $form->getErrors()), Codes::HTTP_INTERNAL_SERVER_ERROR);
}

我得到了这个500错误,这实在是太无用了:

{"formErrorIterators":{"errors":{"form":{"children":{"title":[],"type":[],"summary":[],"description":[],"url":[],"image":[],"date":{"children":{"date":{"children":{"year":[],"month":[],"day":[]}},"time":{"children":{"hour":[],"minute":[]}}}},"creator":[],"issue":[]}},"errors":[]}}}

我认为$ Request没有被正确发送或接收,因为在某些时候我停用了csrf保护,而且Doctrine想要创建一个只有空字段的实体。

这是我的config.yml:

fos_rest:
    routing_loader:
        default_format: json
    param_fetcher_listener: true
    body_listener:
        array_normalizer: fos_rest.normalizer.camel_keys
    body_converter:
        enabled: true
    format_listener:
        rules:
          - { priorities: ['json'], fallback_format: json, prefer_extension: false }
    view:
        view_response_listener: force

有什么想法? 感谢

1 个答案:

答案 0 :(得分:1)

好的,原来有几个错误:

首先,JSON有效负载格式错误:

{"title":"foo","summary":null,"description":"foo","url":"foo","image":null,"issue":"1","creator":"1"}

(我删除了节点的名称)

然后,类型描述符不正确:

        $builder
        ->add('title', 'text')
        ->add('type', 'text')
        ->add('summary', 'text')
        ->add('description', 'text')
        ->add('url', 'text')
        ->add('image', 'text')
        ->add('date', 'date')
        ->add('creator',  'entity', array(
              'class' => 'AppBundle:User')
             )
        ->add('issue',  'entity', array(
                'class' => 'AppBundle:Issue')
        )
    ;

我添加了类型和实体以使其正常。

我对更精确的错误代码更满意。