簡體   English   中英

AngularJS無法從PHP獲取HTTP標頭

[英]AngularJS unable to get HTTP Headers from PHP

我試圖從來自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瀏覽器檢查器中,我可以單擊頁面答復,並查看標題,包括“ Set-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:未定義不是函數

console.log(headers());

結果-> TypeError:未定義不是函數

我還嘗試使用angular-cookies(安裝Bower之后,在索引中添加腳本標簽,注入$ cookies和$ 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); }) 

您將其與success函數和error函數混合在一起,后者與返回的相同諾言相關。

編輯:
從問題中更新代碼段:

 $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]的值作為參數名稱。 如果是這樣的話,上面的代碼將無法為您提供幫助,那么您需要單獨提取它(不在此行中,而是在之前創建參數):

 // 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; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM