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

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

dongzhong5967
dongzhong5967 尝试console.log(response.message[0])并查看它是否打印出您的第一条消息
大约 5 年之前 回复
doucang8303
doucang8303 例如:{“success”:true,“message”:“用户123成功创建”}
大约 5 年之前 回复
dongzha2525
dongzha2525 api和被叫的页面在同一台服务器上,但我不知道更多细节。你能澄清一下你认为可能出现的问题吗?
大约 5 年之前 回复
dongmo2324
dongmo2324 你的json究竟是什么样的?
大约 5 年之前 回复
duandaodao6951
duandaodao6951 改变了,但没有帮助
大约 5 年之前 回复
dongxiongshi9952
dongxiongshi9952 在发出请求时,尝试从响应中打印特定内容,例如response.data.id,这将显示它是否正确进入。显然,使用你自己的JSON
大约 5 年之前 回复
douzi2749
douzi2749 api是否与页面制作请求相同的域,协议和端口?
大约 5 年之前 回复
douji1077
douji1077 不要使用.success使用。然后。.success已折旧。
大约 5 年之前 回复

1个回答

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");
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐