Guide on saving a PDF file after receiving a binary response using axios

Is there a way to save a PDF file from a binary response received through an axios get request?

When making the request, I include the following headers:

const config: AxiosRequestConfig = {
  headers: {
    Accept: 'application/pdf',
    responseType: 'arraybuffer',
  },
};

After receiving the binary response, I would like to download it using the file-saver library, specifically its saveAs function.

Answer №1

Here's my solution to the problem:

async function generateReport(id: number): Promise<void> {
 const configOptions: AxiosRequestConfig = {
  responseType: 'blob',
  headers: {
    Accept: 'application/pdf',
  },
 };

 return axios
  .get(`${BASE_URL}/${id}`, configOptions)
  .catch((error: AxiosError) => handleError(error))
  .then((response: AxiosResponse) => {
    FileSaver.saveAs(new Blob([response.data]), `Report_${id}.pdf`);
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to sort an array of objects based on their properties?

I am working with an array of objects: let response = [{"id": 1, "name": "Alise", "price": 400, "category": 4}]; In addition to the array of objects, I have some arrays that will be used for filtering: let names = ["Jessy", "Megan"]; let prices = [300, ...

Tips on Importing a Javascript Module from an external javascript file into an <script> tag within an HTML file

I'm facing an issue while attempting to import the 'JSZip' module from an external node package called JSZip in my HTML File. The usual method of importing it directly using the import command is not working: <script> import ...

Can someone assist me in creating mongoose models?

Currently, I am focused on managing products and categories These are the two types I have created: type Category = { parent: Category | null; // Is this acceptable? name: String; }; type Product = { categories: Category[]; name: String; ...

TS1055 occurs when utilizing async/await with a custom type alias

I defined a custom type alias: export type ActivationPromise = Promise<void>; I have created the following two functions: async function derp(): ActivationPromise { await test(); } function test(): ActivationPromise { return Promise.resol ...

Tips for accessing the app instance within a module in Nest.js

Currently, I am involved in a project that relies on multiple Nest repositories, approximately 4 in total. Each repository must integrate logging functionalities to monitor various events such as: Server lifecycle events Uncaught errors HTTP requests/resp ...

Troubleshooting a NextJs/TS problem with importing ESM modules

Click here for the Code Sandbox I'm currently in the process of transitioning some code to NextJS 11 / Webpack 5, including certain modules that now exclusively support ECMAScript Modules (esm). Prior to the upgrade, I could easily export all files ...

Retrieving decimal value from a given string

Currently, I am working with Google Maps and encountering an issue with distance values being returned as strings like 1,230.6 km. My goal is to extract the floating number 1230.6 from this string. Below is my attempted solution: var t = '1,234.04 km ...

Ways to deduce or implement intellisense for parameter types in overloaded functions

Currently, I am developing an Electron application where numerous events are being passed around with specific listeners assigned to each event. One example is BrowserWindow.on: Electron.BrowserWindow.on(event, listener) The event can take on values such ...

How can I ensure that a particular component type passes the typescript check in a react-typescript project?

I'm fairly new to using TypeScript, although I have a lot of experience with React (and prop-types). Recently, I've run into an issue when it comes to typing my components, specifically when another component is passed as a prop. I already have ...

Angular 2's abstract component functionality

What are the benefits of utilizing abstract components in Angular 2? For example, consider the following code snippet: export abstract class TabComponent implements OnInit, OnDestroy {...} ...

Assign object properties to a constant variable while validating the values

When receiving the features object, I am assigning its values to constants based on their properties. const { featureCode, featureSubType, contentId, price, family: { relationCountsConfig: { motherCount, fatherCount, childrenCount }, max ...

What is the process for modifying object information using string input in typescript?

How can I update an object's value in TypeScript based on a string input related to the object key? const objData = { // random value A: 11, B: 13, C: 53, innerObj: { AStatus: true, BStatus: false, CStatus: true, }, }; type Item ...

What is causing the issue with using transition(myComponent) in this React 18 application?

Recently, I have been immersed in developing a Single Page Application using the latest version of React 18 and integrating it with The Movie Database (TMDB) API. My current focus is on enhancing user experience by incorporating smooth transitions between ...

What is the best approach for utilizing Inheritance in Models within Angular2 with TypeScript?

Hey there, I am currently dealing with a Model Class Question and a ModelClass TrueFalseQuestion. Here are the fields: question.model.ts export class Question { answerId: number; questionTitle: string; questionDescription: string; } truefals ...

Looping through NavItems component using JavaScript or Angular

My Angular project includes a navbar component with an app sidebar that has a navItems attribute. Below is the content of my navBar: <app-header style="background-color : #e65100;" [fixed]="true" [navbarBrandFull]="{ src: &a ...

The type 'undefined' cannot be assigned to type 'Element or null'

One of the components I am using looks like this: const data: any[] = [] <Tiers data={data}/> This is how my component is structured: const Tiers = ({ data, }: { data?: any; }) => { console.log('data', data?.length!); ...

Having trouble establishing a connection with the C# Controller when processing the frontend request

Having trouble implementing the Search by siteId functionality using typescript and C#. The issue arises when trying to connect to the C# controller from the frontend request. The parameter I need to pass is siteId. Below is the code snippet: HTML: ...

What steps can be taken to resolve the issue of being unable to rename an element in Typescript?

Why does VS code editor sometimes prevent me from renaming my typescript symbol using the f2 key? I keep encountering the error message "This element cannot be renamed." https://i.stack.imgur.com/mmqu9.png In some of my other projects, I am able to renam ...

Issue posting data to localhost using ReactJS remains unresolved

I've been diving into ReactJs and NodeJS recently, and I encountered an issue with my signup page. When I try to post data to the server, it seems to be stuck in a pending state. Is there something specific I might have overlooked or done incorrectly ...

Angular 6 provides a regular expression that specifically targets the removal of any characters that are not numbers and enforces the allowance of

I have tried various solutions to restrict input in an Angular material input box, but none seem to be effective for my specific case. I need the input field to only allow numbers and a decimal point. Any other characters should be automatically removed as ...