【问题标题】:php sending post request to slim framework apiphp 向 slim 框架 api 发送 post 请求
【发布时间】:2018-03-27 22:30:45
【问题描述】:

我正在使用 php slim 框架来构建一个 api,用于插入、更新、删除和显示存储在 mysql 数据库中的数据,现在显示数据工作正常,但是当我尝试插入时它不起作用,这是苗条代码:

$app->post('/api/v1/InsertOrder', function (Request $request, Response $response){
$item_name = $request->getParam("item_name");
$quantity  = $request->getParam("quantity");
$status    = $request->getParam("status");
$sql = "INSERT INTO orders(item_name, quantity, status)VALUES(:item_name, :quantity, :status)";
try {
    $db = DB::connect();
    $stmt = $db->prepare($sql);
    $stmt->bindParam("item_name", $item_name);
    $stmt->bindParam("quantity", $quantity);
    $stmt->bindParam("status", $status);
    $stmt->execute();
    $db = null;
    $res = array("success" => "one row added successfully");
    return json_encode($res);
} catch(PDOException $e) {
    echo '
        {
            "error": {
                "text": '.$e->getMEssage().'
            }
        }
    ';
}

});

这是尝试插入数据的代码

function CallAPI($method, $api, $data=null) {
$url = "http://localhost/set-api-app/public/api/v1/" . $api;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
$response = curl_exec($curl);
$data = json_decode($response);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// Check the HTTP Status code
switch ($httpCode) {
    case 200:
        $error_status = "200: Success";
        return ($data);
        break;
    case 404:
        $error_status = "404: API Not found";
        break;
    case 500:
        $error_status = "500: servers replied with an error.";
        break;
    case 502:
        $error_status = "502: servers may be down or being upgraded. Hopefully they'll be OK soon!";
        break;
    case 503:
        $error_status = "503: service unavailable. Hopefully they'll be OK soon!";
        break;
    default:
        $error_status = "Undocumented error: " . $httpCode . " : " . curl_error($curl);
        break;
}
curl_close($curl);
echo $error_status;
die;
}
$data = array('item_name'=>"new item 2",'quantity'=>199,'status'=>"paid2");
$result = CallAPI('POST', "InsertOrder", $data);

上面的代码没有插入数据,但是当我使用 Web 服务客户端时它可以工作

【问题讨论】:

  • 您的日志、Apache、MySQL 等是否有任何错误?
  • 没有错误只是空白页
  • URL 路径中不应包含publichttp://localhost/set-api-app/api/v1/

标签: php api web-services slim


【解决方案1】:

Content-Type 标头设置为application/json,否则 Slim 无法解码 POSTed JSON 数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-15
    • 2019-03-29
    • 2016-05-12
    • 2015-01-26
    • 2013-07-11
    • 2018-04-04
    • 2014-05-02
    • 1970-01-01
    相关资源
    最近更新 更多