gpt4 book ai didi

php - Angular $http 总是从 PHP API 返回空数据

转载 作者:搜寻专家 更新时间:2023-10-31 21:25:32 24 4
gpt4 key购买 nike

我正在尝试使用我的一位开发人员为我创建的登录 API。

$http({
method: 'POST',
url: "http://example.com/api/userLogin",
data: $.param(postLoginData),
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
responseType: 'json'
}).then(function(loginData) {
console.log(loginData);
});

我的 console.log() 总是记录以下内容:

Object {data: null, status: 200, config: Object, statusText: "OK"}

然而,当我转到开发人员工具中的 Network 选项卡时,我可以看到响应实际上如下:

enter image description here

我不是后端开发人员,所以我对响应开头的这个0有点困惑。然后我尝试进一步调查并查看 PHP API 代码本身,发现 curl_exec($loginCurl) 返回的响应是:

HTTP/1.1 100 Continue

HTTP/1.1 200 OK
Date: Mon, 09 May 2016 02:10:35 GMT
Server: Apache/2.4.7 (Ubuntu)
X-Powered-By: PHP/5.5.9-1ubuntu4.14
Cache-Control: no-cache
Content-Length: 43
Content-Type: application/json

{"id":"16","username":"user4","status":200}

响应的 body 是有效的 JSON,所以不太确定 Angular 返回空数据的原因,即使我可以在开发人员工具中成功看到响应...


编辑:

我的 API 包含以下内容以执行检查和创建 session :

$jsonResults = json_decode($body, true);
if($jsonResults != NULL || $jsonResults->id != NULL) {
//Successfully logged in
$_SESSION['user_name'] = $jsonResults->username;
$_SESSION['user_login_status'] = 1;
$_SESSION['user_id'] = $jsonResults->id;

$this->response($body, 200);
}

虽然,如果将上面的整个代码替换为以下代码,它似乎工作得很好:

$this->response($body, 200);

为什么会这样?

最佳答案

问题肯定是服务器端的,但是您可以使用响应转换器来解决它。例如……

$http.post('http://example.com/api/userLogin', $.param(postLoginData), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
transformResponse: function(data) {
console.log('Raw data', data);
if (angular.isString(data) && data[0] === '0') {
data = data.substring(1);
}
return angular.fromJson(data);
}
}).then(function(response) {
console.log(response);
})

关于php - Angular $http 总是从 PHP API 返回空数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37106915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com