Search code examples
javascriptrestfetch

Cannot get response header fetch request even with Access-Control-Expose-Headers


I am trying to get the x-total-count response header from a fetch JS request, I have included Access-Control-Expose-Headers as advised in other previous posts and I am still unable to get the response header, I can see it is being received in chrome dev tools and have tried response.headers.get('x-total-count'); and iterating over response.headers with no luck.

What am I missing here?

async function postData() { 
      const myPost = {
          "listingType":"Sale",
          "propertyTypes": [
              "townhouse",
              "duplex",
              "semiDetached",
              "studio",
              "townhouse",
              "villa",
              "ApartmentUnitFlat",
              "Rural",
              "house"
            ],
          "geoWindow": {
            "box": {
              "topLeft": {
                "lat": aNorth,
                "lon": aWest
              },
              "bottomRight": {
                "lat": aSouth,
                "lon": aEast
              }
            },
          },
          "pageNumber": pageNumber,
          "pageSize": 100
        }
        
        const options = {
          method: 'POST',
          body: JSON.stringify(myPost),
          headers: {
            'Content-Type': 'application/json',
            "X-API-Key": "API-KEY",
            'Access-Control-Expose-Headers': 'x-total-count'
          }
        };

        const response = await fetch('https://api.domain.com.au/v1/listings/residential/_search', options)
        if (!response.ok) {
          const message = `An error has occured: ${response.status}`;
          throw new Error(message);
        }

        const totalCount = response.headers.get('x-total-count');

        for (var pair of response.headers.entries()) { console.log(pair[0]+ ': '+ pair[1]); }

        console.log(totalCount)


Solution

  • As an updated I contacted the team that runs this API and received the following response below, turns out it was an issue on their end.

    It would appear you've run into an issue with our early support for CORS requests, the header you are trying to set, Access-Control-Expose-Headers, is actually one that we specify from our side.

    Presently we don't specify it completely, so the x-total-count header is not exposed to browsers which follow the CORS rules.

    I have added this issue to our backlog to be rectified as soon as possible, and it will most likely will be part of our first planned update in early January 2021.