对 php RestApi 的 Http 调用从 angular 需要 15 秒,而从邮递员只需 20 毫秒。我错过了什么?

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

使用 slim 框架从 angular http 向本地 Apache 2.4 服务器 运行 php restapi 发出请求。请求需要 15 秒以上才能返回。但是,当我使用邮递员测试 api 时,响应需要 20 毫秒,这正是我所期望的。我是 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);
    });

尝试通过发送以下内容来关闭连接 header:

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

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

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