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 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。