对phpRestApi的Http调用从angular需要15秒,从poster只需要20秒.我错过了什么


Http calls to php RestApi take 15sec from angular and only 20ms from postman. What am I missing?

从angular http向本地Apache 2.4服务器发出请求,该服务器运行带有瘦框架的php restapi。请求需要15秒以上才能返回。然而,当我使用poster测试api时,响应需要20ms,这正是我所期望的。我是php的新手,是否缺少一些配置?

<?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;
}

请求

$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);
    });

尝试通过发送以下标头来关闭连接:

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

但首先,使用setBody()方法设置响应主体,而不是使用echo:

$app->response->setBody(json_encode($data));