我在Symfony 4项目中实现了一个简单的REST API。当我用邮递员测试getArticle()函数时,这是错误消息:
控制器必须返回响应(给定的Object(FOS \ RestBundle \ View \ View))。
使用var_dump($ articles)内容将按预期显示,因此我想问题可能出在FOSRestBundle上,但是我不知道执行此工作的其他方法。
class ArticleController extends FOSRestController
{
/**
* Retrieves an Article resource
* @Rest\Get("/articles/{id}")
*/
public function getArticle(int $articleId): View
{
$em = $this->getDoctrine()->getManager();
$article = $em->getRepository(Article::class)->findBy(array('id' => $articleId));
// In case our GET was a success we need to return a 200 HTTP OK response with the request object
return View::create($article, Response::HTTP_OK);
}
}
我自己找到了返回HttpFoundation \ Response的解决方案,这可能对某人有所帮助。
/**
* Lists all Articles.
* @FOSRest\Get("/articles")
*/
public function getArticles(Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$articles = $em->getRepository(Article::class)->findAll();
return new Response($this->json($articles), Response::HTTP_OK);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句