reactjs Symfony API不返回任何响应

sczxawaw  于 2023-05-22  发布在  React
关注(0)|答案(1)|浏览(131)

当尝试将Symfony API与React应用程序连接时,会出现API拒绝返回任何响应的问题。但是,当直接访问API链接时,会正确返回响应。
ApiDirectURL
但是,尝试通过React应用程序获取这些数据不会返回任何内容。

const api_url = "http://127.0.0.1:8000/app-api/";
  const farmid = "1234567890123456789012345678901234567890";
  
  async function getFarmInfo() {
    const response = await fetch(api_url + farmid + "/info",{
      cache: "no-store", 
      mode: "no-cors",
      method: "GET",
      headers: {
        "Accept": "application/json"
      }});
    const jsonData = await response.json();
    console.log(jsonData);
  }

ServerResponse
未响应API代码

#[Route('/info', name: 'info')]
    public function info(Request $request,EntityManagerInterface $em,$fishingfarmid): Response
    {

        $farm = $em->getRepository(FishingFarm::class)->findOneBy(["trueId" => $fishingfarmid]);
        $json = ["phone" => $farm->getPhone() , "regulation" => $farm->getRegulations() , "email" => $farm->getEmail() , "address" => $farm->getAddress()];
        return new JsonResponse($json);
    }

然而,我偶然发现,如果我使用var_dump(“”);函数的某个地方,React代码中的响应突然出现。

#[Route('/info', name: 'info')]
public function info(Request $request,EntityManagerInterface $em,$fishingfarmid): Response
{

    $farm = $em->getRepository(FishingFarm::class)->findOneBy(["trueId" => $fishingfarmid]);
    $json = ["phone" => $farm->getPhone() , "regulation" => $farm->getRegulations() , "email" => $farm->getEmail() , "address" => $farm->getAddress()];
    var_dump("");
    return new JsonResponse($json);
}

var_dump的结果

m3eecexj

m3eecexj1#

我不知道为什么,但它的作品后删除mode: "no-cors"

async function getFarmInfo() {
    const response = await fetch(api_url + farmid + "/info",{
      method: "GET",
     });
    const jsonData = await response.json();
    
    setFarmInfo( jsonData);
  }

相关问题