【问题标题】:Symfony: fetch with put request on route results in RuntimeExceptionSymfony:在 RuntimeException 中使用 put 请求获取路由结果
【发布时间】:2019-01-08 15:48:19
【问题描述】:

我正在尝试通过使用以下代码单击按钮来调用服务方法:

树枝 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>

【问题讨论】:

  • twig HTML 是如何呈现的?请提供浏览器源视图中显示的最终 HTML。另外,您确定需要使用 PUT 作为方法吗?因为那个 URL 参数是一个 GET 参数,afaik。 PUT 参数在正文中,就像 POST 参数一样。
  • 你有没有试过把 html 改成这个 onclick="ready('{ path: 'ready/name'}')"
  • @ÁlvaroTouzón Twig 使用 {{ var }} 将值插入 HTML。
  • 我看到形成的 uri 需要是:“/api/player/ready/Testname”你配置了 httdocs 吗?
  • @ChrisG 我添加了最终的 HTML。我觉得应该是PUT方法,因为我调用的service方法更新了一个缓存条目

标签: javascript php symfony twig httpresponse


【解决方案1】:

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

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

    return new Response('test');
}

【讨论】:

    猜你喜欢
    • 2017-02-02
    • 2011-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    • 2013-03-08
    • 2022-08-19
    相关资源
    最近更新 更多