简体   繁体   中英

CakePhp: Got erros in response body when calling an API with the CakePHP HttpClient

I'm having some HTML text in my response from an API.

Response I got

在此处输入图片说明

Preview's response

在此处输入图片说明

Here is my code (PHP):

    public function getBeatmapInformations() {
    $this->render(false);
    if($this->request->is('get')){
        $url = $_GET['beatmapUrl'];
        $isOsuUrlBeatmap = "#^(?:https://)?osu\.ppy\.sh/(?:b|beatmapsets)/(\d*)#";
        if(preg_match($isOsuUrlBeatmap, $url, $matches)){
            $OSU_API_KEY = "MY_API_KEY";
            $httpClient = new Client();
            $response = $httpClient->get('https://osu.ppy.sh/api/get_beatmaps', [
                    's' => intval($matches[1]),
                    'k' => $OSU_API_KEY
                ]
            );
            $result = $response->body();
            if(!empty($result)){
                echo $result;
            }
        }
    }
}

Javascript side (AJAX request):

function launchAjaxRequest(beatMapUrl) {
let url = beatMapUrl.replace(/['"]+/g, '');
$.get({
    type : "GET",
    url: '/ofv/getBeatmapInformations',
    data: {
        beatmapUrl : url,
    },
    success: function(data){
       fillModesAvailablesForBeatmap(data);
    }
});}

You should not manually echo anything in your controllers actions in CakePHP. The way to achieve json output in CakePHP is to use Data Views with Request Handler:

1.Enable Request Handler in your controller's initialize() method:

public function initialize(){
    $this->loadComponent("RequestHandler");
}

2.In your action, set your data to be serialized:

$result = $response->body();
$this->set(compact("result"));
$this->set("_serialize", "result");

More about Request Handler and Data Views can be found in docs: JSON and XML views

As probably someone will point it out, you have also an alternative here: you can simply stop execution of script right after echoing data with die(). But it is not the Cake way of handling this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM