pt2t
pt2t

Reputation: 473

Download CSV files with HttpClient in ReactJS

I'm trying to make an API request using HttpClient to download a CSV file. I had to switch from Axios to HttpClient due to ForgeRock authentication that requires a bearer token. I'm having an issue where the response coming back does not have response.data. Where would I find the data to download to CSV?

My code:

fetchCSV = date => {
    const url = "https://<URLdownloadLink>?runDate="+date;
    const method = "GET";
    HttpClient
      .request({
        url,
        method,
        bypassAuthentication: false,
        responseType: 'blob',
        init: {},
        timeout: 5000
      })
      .then((response) => {
        console.log("data", response)
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'Asset Manager.csv');
        document.body.appendChild(link);
        link.click();
        link.remove();
      })
      .catch(error => {
        console.log("error", error);
      })
  }

The response I'm getting back is the below. The response does not have "response.data" as an object key. When I open the CSV it only has "undefined". enter image description here

This is my response.body: enter image description here

Upvotes: 1

Views: 2657

Answers (1)

Njuguna Mureithi
Njuguna Mureithi

Reputation: 3856

You are using response.data instead of response.body? Thats why it says undefined. Remember CSV is just plain text and response.data is undefined.

fetchCSV = date => {
    const url = "https://<URLdownloadLink>?runDate=" + date;
    const method = "GET";
    HttpClient
        .request({
            url,
            method,
            bypassAuthentication: false,
            responseType: 'blob',
            init: {},
            timeout: 5000
        })
        .then((response) => {
            console.log("data", response)
            const url = window.URL.createObjectURL(new Blob([response.body]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', 'Asset Manager.csv');
            document.body.appendChild(link);
            link.click();
            link.remove();
        })
        .catch(error => {
            console.log("error", error);
        })
}

Upvotes: 1

Related Questions