Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading response headers with Fetch API

I'm in a Google Chrome extension with permissions for "*://*/*" and I'm trying to make the switch from XMLHttpRequest to the Fetch API.

The extension stores user-input login data that used to be put directly into the XHR's open() call for HTTP Auth, but under Fetch can no longer be used directly as a parameter. For HTTP Basic Auth, circumventing this limitation is trivial, as you can manually set an Authorization header:

fetch(url, {   headers: new Headers({ 'Authorization': 'Basic ' + btoa(login + ':' + pass) })   } }); 

HTTP Digest Auth however requires more interactivity; you need to read parameters that the server sends you with its 401 response to craft a valid authorization token. I've tried reading the WWW-Authenticate response header field with this snippet:

fetch(url).then(function(resp) {   resp.headers.forEach(function(val, key) { console.log(key + ' -> ' + val); }); } 

But all I get is this output:

content-type -> text/html; charset=iso-8859-1 

Which by itself is correct, but that's still missing around 6 more fields according to Chrome's Developer Tools. If I use resp.headers.get("WWW-Authenticate") (or any of the other fields for that matter), i get only null.

Any chance of getting to those other fields using the Fetch API?

like image 759
jules Avatar asked Apr 11 '17 11:04

jules


2 Answers

There is a restriction to access response headers when you are using Fetch API over CORS. Due to this restriction, you can access only following standard headers:

  • Cache-Control
  • Content-Language
  • Content-Type
  • Expires
  • Last-Modified
  • Pragma

When you are writing code for Google Chrome extension, you are using CORS, hence you can't access all headers. If you control the server, you can return custom information in the response body instead of headers

More info on this restriction - https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types

like image 58
Raj Avatar answered Sep 22 '22 09:09

Raj


If it's NOT CORS:

Fetch does not show headers while debugging or if you console.log response.

You have to use following way to access headers.

response.headers.get('x-auth-token') 
like image 24
Nitin Jadhav Avatar answered Sep 22 '22 09:09

Nitin Jadhav