douchanxiu5636 2015-06-23 21:55
浏览 64
已采纳

Http调用php RestApi从角度开始需要15秒,距离邮差只有20毫秒。 我错过了什么?

Making requests from angular http to local Apache 2.4 server running php restapi with slim framework. the requests take 15+ seconds to come back. however when I use postman to test the api the responses take 20ms which is what I expect. I'm brand new to php, is there some configuration I'm missing?

<?php

require 'vendor/autoload.php';
$app = new Slim\Slim();

// ==============================
// Connection ===================
// ==============================

function connect()
{
   $servername = "localhost";
   $username = "root";
   $password = "******";

try {
    $conn = new PDO("mysql:host=$servername;dbname=contacts", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //echo "Connected successfully<br>";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
return $conn;
}

$app->get('/contacts', function () use ($app) {
    getContacts(connect(), $app);
});

$app->run();


function getContacts($conn, $app)
{

$app->response()->header("Content-Type", "application/json");
$app->response()->header('Access-Control-Allow-Origin', '*');
$app->response()->header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
$app->response()->header('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
$app->response()->header('Access-Control-Allow-Credentials', true);

try {
    $stmt = $conn->prepare("SELECT * FROM contacts");
    $stmt->execute();
    echo json_encode($stmt->fetchAll());

} catch (PDOException $e) {
    echo $e->getMessage();
}

$conn = null;
}

The Request

$http({
        method: 'GET',
        url   : "http://localhost/Contacts_PHP/contactsAPI.php/contacts"
    }).success(function (data) {
        $scope.contacts = data;
        console.log($scope.contacts);

    }).error(function (ex) {
        console.log(ex);
    });
  • 写回答

1条回答 默认 最新

  • drjmrg8766 2015-06-24 06:28
    关注

    Try closing the connection by sending the following header:

    $app->response->headers->set('Connection', 'close');
    

    But first, set your response body by using the setBody() method, instead of using echo:

    $app->response->setBody(json_encode($data));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题