AngularJS无法从PHP获取HTTP标头

AngularJS unable to get HTTP Headers from PHP

本文关键字:获取 HTTP 标头 PHP AngularJS      更新时间:2023-09-26

我正试图从来自PHP网站的AngularJS中的http调用中获取一个标头。我打电话给的网站管理员向我保证,CORS已经启用,服务器已经设置了一个标志,允许js访问cookie。这是示例代码:

    $http({
        method: "POST",
        url: 'https://example.com/page',
        data: {'Form[foo]': feild1, 'Form[bar]': field2},
        headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}
    }).then(function(data, status, headers, config) {
        console.log(data.data);
        console.log(headers()['Set-Cookie']); 
    }, function(err) {
        console.error('ERR', err);
    })

在第一条日志评论中,我可以看到返回的网页。在Chrome检查器中,我可以点击回复页面,看到标题,包括"设置Cookie"。然而,第二条日志注释返回:

 TypeError: undefined is not a function

我做了很多寻找答案和试错测试的工作。例如:

  }).then(function(data, status, headers, config) {
        console.log(data.headers);            

结果->

function (name) {
  if (!headersObj) headersObj =  parseHeaders(headers);
  if (name) {
    return headersObj[lowercase(name)] || null;
  }
  return headersObj;
}   

以及:

  }).then(function(resp) {
    console.log(resp.headers["Set-Cookie"]); 

结果->未定义

console.log(resp.header('Set-Cookie')); 

结果->TypeError:undefined不是函数

console.log(headers());

结果->TypeError:undefined不是函数

我还尝试过使用angular cookie(在Bower安装后,在索引中添加脚本标记,注入$cookie和$timeout):

        $timeout(function(){
            console.log($cookies.session)
        });

结果->未定义

还有

console.log($cookieStore.get('Set-Cookie'));

结果->未定义。

我读过很多关于这个问题的问题,但提出的答案都没有奏效。如果有人能为我指明正确的方向,我将不胜感激。

从文档中,您应该能够检索标题,如下所示

console.log(headers('Set-Cookie'));

$http服务返回一个promise,该promise通过一个名为headers的字段的对象来解析,该字段是一个获取标头的函数。

因此,要修复您现有的代码,您需要更改

.then(function(data, status, headers, config) {
        console.log(data.data);
        console.log(headers()['Set-Cookie']); 
    }, function(err) {
        console.error('ERR', err);
    })

.then(function(resolvedObject) {
        console.log(resolvedObject);
        console.log(resolvedObject.headers('Set-Cookie')); 
    }, function(err) {
        console.error('ERR', err);
    })

您将它与successerror函数混合在一起,这两个函数与返回的同一promise绑定在一起。

编辑:
更新问题中的片段:

$http({
        method: "POST",
        url: 'https://example.com/page',
        data: $.param({'Form[foo]': feild1, 'Form[bar]': field2}),
        headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}
    }).then(function(resolvedOcject) {
        console.log(resolvedOcject);
        console.log(resolvedOcject.headers('Set-Cookie')); 
    }, function(err) {
        console.error('ERR', err);
    });

此外,我相信您的意图是使用Form[foo]的值作为参数名称。如果是这样的话,上面的代码不会给你,你需要单独提取它(不在这一行,但之前创建了params):

// As an object
var params = {};
params[Form.foo] = 'field1';
params[Form.bar] = 'field2';
// Or as a query string
var queryString = Form.foo + '=' + field1 + '&' + Form.bar + '=' + field2;