Search code examples
reactjsheaderfetchresponseinterceptor

In React, how do I get the value of a response header in an interceptor?


I'm using React 16 and the fetch-interceptor library. I have this in a file called src/interceptors/fetch.js ...

import fetchIntercept from 'fetch-intercept';

const unregister = fetchIntercept.register({

  response: function (response) {
    console.log("\n\ncalled function!");
    console.log("body:" + response.body);

    // Do something with the response
    console.log(response.headers);
    console.log("header: " + response.headers.get('Refresh-Token') );
    if (response.ok && 'Refresh-Token' in response) {
      const token = response['Refresh-Token'];
      console.log("saving " + token);
      sessionStorage.setItem('token', token)
    }
    return response;
  },

});

In my src/App.js component, I include it like so

import { unregister } from "./interceptors/fetch.js";

but when I make a fetch call, I can't seem to get any headers. The console line

console.log("header: " + response.headers.get('Refresh-Token') );

prints out

header: null

despite the fact in my Chrome Devtools, I see

.   Access-Control-Allow-Origin: http://localhost:3000
.   Allow: POST, OPTIONS
.   Content-Length: 196
.   Content-Type: application/json
.   Date: Tue, 05 Jul 2022 14:48:49 GMT
.   Referrer-Policy: same-origin
.   Refresh-Token: f7c622e042b38a9fc2c594a914c2fe38ffa8fb53
.   Server: WSGIServer/0.2 CPython/3.9.1
.   Vary: Accept, Origin
.   X-Content-Type-Options: nosniff
.   
X-Frame-Options: DENY

under the "Response Headers" section. I get the same result in consolelog if I try and query other types of headers, e.g. "Content-Type". What's the right way to get my header value?

Edit: In response to the answer given, the output of the console log is

.   {content-length: '180', content-type: 'application/json'}
.   content-length: "180"

.  content-type: "application/json"

which is odd that only those two headers are showing up, because from Chrome devtools, there are many more headers (notice the content-length matches)

enter image description here


Solution

  • If you go through the specs of fetch API on MDN, you will see that it has a fixed set of headers that are readable by the scripts for CORS requests, and to allow more headers you will need to add them to the allow list using Access-Control-Expose-Headers(assuming you have access to the server).

    The Access-Control-Expose-Headers response header allows a server to indicate which response headers should be made available to scripts running in the browser, in response to a cross-origin request.
    

    It's not like these headers can't be accessed at all, but the browser will respect the specs and not allow reading non-allowed headers by scripts running on the page. That's why you can see the headers in the network tab but your script is not able to access the custom headers.