With iron-ajax, how to read the headers of a response?
Asked Answered
H

3

10

When a response for a request arrives, is there any way to read the response headers?

Hadria answered 12/6, 2015 at 5:8 Comment(0)
S
11

The response event handlers gets passed the <iron-request> as the second argument. <iron-request> has an xhr property that is the XMLHttpRequest used to make the request. You should be able to get the response headers from that.

<iron-ajax on-response="ajaxResponse"></iron-ajax>
...
ajaxResponse: function(e, request) {
  var headers = request.xhr.getAllResponseHeaders();
}
Snath answered 12/6, 2015 at 5:20 Comment(0)
D
6

If an HTTP request is made over AJAX in javascript, it is possible to get the response headers with the getAllResponseHeaders() method. It's part of the XMLHttpRequest API.

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
alert(headers);

EDIT:

I just noticed the iron-ajax part of question.

<iron-ajax
    url="http://gdata.youtube.com/feeds/api/videos/"
    params='{"alt":"json", "q":"chrome"}'
    handle-as="json"
    on-response="handleResponse"
    debounce-duration="300">
</iron-ajax>
    ...
handleResponse: function(e, request) {
    var headers = request.xhr.getAllResponseHeaders();
    alert(headers)
  }

Hope it helps :)

Dissimulation answered 12/6, 2015 at 5:18 Comment(1)
As a follow up question, how would one determine the method that was used for the request? I can get the xhr.responseURL, but I don't see where I can determine which method was used for the call.Seeress
I
0

As mentioned in Trevor Dixon's answer, iron-ajax provides iron-request object in response handler which exposes XMLHttpRequest as xhr property.

A specific response header can be obtained using getResponseHeader method of XMLHttpRequest.

ironRequest.xhr.getResponseHeader('header name');

All headers can be obtained using getAllResponseHeaders method of XMLHttpRequest which is rarely used since we mostly don't want to read all headers at once.

Issuable answered 28/6, 2019 at 10:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.