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条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?