简体   繁体   中英

How to get http response content of Slim PHP Api with Angular JS?

I have an API programmed with Slim PHP which sends JSON responses like this:

$response['some-text'] = 'blabla';
$app->response->setStatus(200);
$app->response()->headers->set('Content-Type', 'application/json');
echo json_encode($response, JSON_UNESCAPED_UNICODE);

Now when I open an API url in a browser, the message is displayed as wanted. However, if I open the same url with my ionic app using angular JS like this:

$http.get("URL").success(function(response) {console.log(response)});

when I check the console afterwards, I only see the code (200) but no JSON with the message. However, I'm sure that the API did receive the call correctly, as actions like adding items to a database are executed just fine. But how can I get the response?

/edit Here is a screenshot from the console, what the empty response looks like

header: http://i.imgur.com/CCawaIA.jpg

answer: http://i.imgur.com/xo46MpJ.jpg

I found a solution. While I'm not sure it is a good one, it certainly works.

I added this code to my response function in php:

$app->response()->headers->set('Access-Control-Allow-Origin', '*');
$app->response()->headers->set('Access-Control-Allow-Methods', 'GET'); //or whatever you need
$app->response()->headers->set('AAccess-Control-Allow-Headers', 'X-Requested-With');

which, if you don't use slim php, should be equal to:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header("Access-Control-Allow-Headers: X-Requested-With");

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