dongtao9095 2018-11-27 21:20
浏览 81
已采纳

使用Slim Framework 3 Skeleton获取REST API

I am learning how to build an API using PHP and Slim Framework, I made a test called "data" to get an array:

header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: text/html; charset=utf-8');
header('P3P: CP="IDC DSP COR CURa ADMa OUR IND PHY ONL COM STA"');

error_reporting(1);

require '../../slim/vendor/autoload.php';
$app = new \Slim\App;

function response($status_code, $response) {
    $app = \Slim\App::getInstance();
    $app->status($status_code);

    $app->contentType('application/json');
    return json_encode($response);
}

$app->get('/data', function () {

    $response = array();

    $data=array(
        array('Foo'=>'Foo', 'Bar'=>'Bar'),
        array('Lorem'=>'Ipsum', 'Dolor'=>'Sit Amet')
    );

    $response["error"] = false;
    $response["message"] = "datas: " . count($data);
    $response["data"] = $data;

    return response(200, $response);
});

When I call the api using /data I got a status 200 empty response.

This is the url: http://sandboxweb.bailac.net/gts_benja/api/v1/data

What is wrong and what I need to do to get the array?

  • 写回答

2条回答 默认 最新

  • douhanshu5517 2018-11-28 14:17
    关注

    Well, I finally got it, Slim 3 needs return a slim object (like body, write and withJson), the following code works for me:

    $app->get('/data', function ($request, $response){
    
        $data=array(
            array('Foo'=>'Foo', 'Bar'=>'Bar'),
            array('Lorem'=>'Ipsum', 'Dolor'=>'Sit Amet')
        );
    
        return $response->withJson($data);
    });
    

    the followings ways to return worked for me too:

    return $response->body(json_encode($data));
    return $response->write(json_encode($data));
    

    I prefer withJson method to avoid using json_encode.

    Thank you Alex Howansky for your help!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler