当我使用“php bin/console debug:router”命令时,我得到以下结果:
命名方法方案主机路径
_preview_error ANY ANY ANY /_error/{code}.{_format}
所以这意味着我的路由没有被找到。我希望/和/add-sample路由在那里。
访问http://127.0.0.1:8000/api/parties上的端点时出现404错误Symfony\Component\Routing\Exception\ ResourceNotFoundException
No routes found for "/api/parties/".
我的路由未被识别的原因是什么?
**:
app_party:
resource: App\Controller\PartyController
type: annotation
PartyController.php:
<?php
namespace App\Controller;
use App\Entity\Party;
use App\Repository\PartyRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("/api/parties", name="app_party_api_parties")
*/
class PartyController
{
/**
* @Route("/", name="api_party_list", methods={"GET"})
*/
public function list(PartyRepository $partyRepository): JsonResponse
{
$parties = $partyRepository->findAll();
$data = [];
foreach ($parties as $party) {
$data[] = [
'id' => $party->getId(),
'name' => $party->getName(),
'ideology' => $party->getIdeology(),
// Add more properties as needed
];
}
return new JsonResponse($data);
}
/**
* @Route("/add-sample", name="api_party_add_sample", methods={"POST"})
*/
public function addSampleParty(EntityManagerInterface $entityManager): JsonResponse
{
$party = new Party();
$party->setName('Sample Party');
$party->setIdeology('Some Ideology');
$party->setLeader('Sample Leader');
$entityManager->persist($party);
$entityManager->flush();
return new JsonResponse(['message' => 'Sample party added successfully.']);
}
}
1条答案
按热度按时间iyzzxitl1#
我通过运行
composer require annotations
并更新PartyController.php
修复了这个问题: