View all our code samples

Using Axios in Node

Axios is a popular Promise-based HTTP client for Node.js and the browser. It provides an easy-to-use API for making HTTP requests and handling responses asynchronously. Axios supports features like request and response interceptors, automatic JSON data transformation, and request cancellation.

We've implemented a code sample that you can re-use to convert your HTML documents to PDF, JPG, PNG or WEBP using PDFShift and Node:

const axios = require('axios');

async function convert(api_key, params, endpoint = 'pdf') {
    if (!['pdf', 'png', 'jpg', 'webp'].includes(endpoint)) {
        throw new Error('Invalid endpoint');
    }

    try {
        const response = await axios.post(`https://api.pdfshift.io/v3/convert/${endpoint}`, params, {
            auth: {
                username: 'api',
                password: api_key
            }
        });

        if (params.filename || params.webhook) {
            // Return JSON in this case
            return response.data;
        }

        // Returns the binary data
        return response.data;

    } catch (error) {
        console.error(error);
    }
}

Here's how you can use the above code:

let binary = await convert('sk_XXXXXXXXXXXXXX', {source: 'https://en.wikipedia.org/wiki/REST'});
require('fs').writeFileSync('result.pdf', binary);

We've tested this code with the latest version of Axios and it's ready to be used in your project.

But if you were to encounter any bugs or issues while running it (or if you want to suggest changes to improve the code), please contact us and we'll be happy to help you out.