Skip to content Skip to sidebar Skip to footer

Using Js To Consume A Rails Send_data Response

I have a VueJS frontend that is connected to a Rails API backend. In one of the endpoints, I am using WickedPDF to generate a PDF. When I open the URL itself in a browser, the PDF

Solution 1:

If you are using axios for the API call, you can specify the client to download the data as blob.

import axios from'axios';

axios
    .request({
       url: '/api-url-to-download-pdf',
       responseType: 'blob',
    })
    .then(response => response.data)
    .then(blob => {
        const data = URL.createObjectURL(blob );

        // ... do your stuff here ...
    .catch((err) => {
        // handle error
    });

If you are using fetch api to make the API request,

fetch('/api-url-to-download-pdf', {
    headers: {
        Accept: 'application/pdf',
    },
    responseType: 'arraybuffer'
})
    .then(response => {
        console.log(response);
        if (response.ok) {
            return response.blob();
        }
    })
    .then(blob => {
        const data = URL.createObjectURL(blob);

        // ... do your stuff here ...
    })
    .catch((err) => {
        // handle error
    });

Post a Comment for "Using Js To Consume A Rails Send_data Response"