【问题标题】:Silex - My REST POST/PUT calls aren't receiving parametersSilex - 我的 REST POST/PUT 调用未接收参数
【发布时间】:2015-08-14 14:59:42
【问题描述】:

我目前在 Silex 1.3 中使用 Doctrine DBAL 2.5 版对 MySQL DB 进行 REST 调用。我设法让我的 GET / GET/{id} 和 DELETE/{id} 相当容易地工作,但我似乎无法让我的 POST/PUT 工作。

这里是闲置代码

$app->post('/student', function($firstName, $lastName) use($app) {
    $sql = "INSERT INTO tbl_students (firstName, lastName)
            VALUES (:firstName, :lastName)";
    $student = $app['db']->prepare($sql);
    $student->bindValue(':firstName', $firstName, PDO::PARAM_STR);
    $student->bindValue(':lastName', $lastName, PDO::PARAM_STR);

    $student->execute();

    return "insert successful";
});

$app->put('/student/{id}', function($id, $firstName, $lastName) use($app){
    $sql = "UPDATE tbl_students 
            SET firstName = :firstName, lastName = :lastName 
            WHERE id = :id";
    $student = $app['db']->prepare($sql);
    $student->bindValue(':id', $id, PDO::PARAM_INT);
    $student->bindValue(':firstName', $firstName, PDO::PARAM_STR);
    $student->bindValue(':lastName', $lastName, PDO::PARAM_STR);
    $student->execute();

    return "student succesfully updated";
});

如果我对默认值进行硬编码,它可以很好地工作,也可以使用 bindParam() 和我自己的值。

在我的 curl 将所有内容转储给我后,我不断收到此错误消息

<span class="exception_message">Controller &quot;Closure&quot; requires that you provide a value for the &quot;$firstName&quot; argument (because there is no default value or because there is a non optional argument after this one).</span>

这是我使用过的休闲 curl 命令

curl -X POST -d "firstName=First123&lastName=Last456" URL/student
curl -X POST -d '{"firstName":"First123","lastName":"Last456"}' URL/student --header "Content-Type:application/json"
curl -X POST -d "firstName=First123&lastName=Last456" URL/student --header "Content-Type:text/html"

【问题讨论】:

  • firstNamelastName 不属于您的路线 - 因此您会收到该错误消息。您必须从Request 阅读这些内容,或者将它们包含在您的路线中。

标签: rest symfony post curl doctrine-orm


【解决方案1】:

Silex 不会自动为您的方法创建与您的帖子变量相对应的参数。您必须按照@Artamiel 的建议从请求对象中获取它们。

http://silex.sensiolabs.org/doc/usage.html#example-post-route

你的 post 操作的更新代码应该是这样的:

$app->post('/student', function(Request $request) use($app) {
    $firstName = $request->get('firstName');
    $lastName = $request->get('lastName');
    $sql = "INSERT INTO tbl_students (firstName, lastName)
            VALUES (:firstName, :lastName)";
    $student = $app['db']->prepare($sql);
    $student->bindValue(':firstName', $firstName, PDO::PARAM_STR);
    $student->bindValue(':lastName', $lastName, PDO::PARAM_STR);

    $student->execute();

    return "insert successful";
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 2010-12-25
    • 2012-09-26
    • 1970-01-01
    相关资源
    最近更新 更多