简体   繁体   English

如何使用Angular JS获取Slim PHP Api的http响应内容?

[英]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: 我有一个使用Slim PHP编程的API,它可以像这样发送JSON响应:

$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. 现在,当我在浏览器中打开API网址时,该消息将按需要显示。 However, if I open the same url with my ionic app using angular JS like this: 但是,如果我使用角度JS用离子应用程序打开相同的网址,如下所示:

$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. 之后,当我检查控制台时,仅看到代码(200),但消息中没有JSON。 However, I'm sure that the API did receive the call correctly, as actions like adding items to a database are executed just fine. 但是,我确信该API确实能够正确接收到该调用,因为可以很好地执行将项目添加到数据库之类的操作。 But how can I get the response? 但是我如何得到答复?

/edit Here is a screenshot from the console, what the empty response looks like / edit这是控制台的屏幕截图,空的响应如下所示

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

answer: http://i.imgur.com/xo46MpJ.jpg 答案: 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: 我将此代码添加到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: 如果您不使用苗条的php,则应等于:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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