Symfony:在RuntimeException中通过路由请求获取请求

时间:2019-01-08 15:48:19

标签: javascript php symfony twig httpresponse

我试图通过单击以下代码的按钮来调用服务方法:

Twig HTML:

<input type="button" value="Ready Up" onclick="ready('{{ path('ready', {'playerName' : name}) }}')">

Javascript:

function ready(path) {
    fetch(path, {method : 'put'})
        .then(function (response) {
            console.log(response);
        });
}

Symfony控制器:

/**
 * @Route("/api/player/ready", name="ready")
 * @return Response
 */
public function toggleReady($playerName) {
    $this->gameCacheService->readyUp($playerName);

    return new Response('test');
}

单击按钮将导致以下异常:

 Uncaught PHP Exception RuntimeException: "Controller "App\Controller\PlayerController::toggleReady()" requires that you provide a value for the "$playerName" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one." 

但是,生成的URL在我看来确实为'$ playerName'提供了一个值:

/api/player/ready?playerName=Testname

是什么原因导致这种行为?

在浏览器中呈现的最终HTML:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    </head>
<body>
    <input type="button" value="Ready Up" onclick="ready('/api/player/ready?playerName=Testname')">
    <script>
        function ready(path) {
            fetch(path, {method : 'put'})
                .then(function (response) {
                    console.log(response);
                });
        }
    </script>
</body>
</html>

1 个答案:

答案 0 :(得分:3)

您忘记在注释中包含路径参数:

/**
 * @Route("/api/player/ready/{playerName}", name="ready")
 * @return Response
 */
public function toggleReady($playerName) {
    $this->gameCacheService->readyUp($playerName);

    return new Response('test');
}
相关问题