Problem with axios and activeCampaign api

317 Views Asked by At

i have created firebase cloud function to create contact in activeCampain. I have problem with catch errors from activeCampaign. If i sent request direct to activeCampain from insomnia everything works correctly, but if i use firebase cloud function with axios something goes wrong.

I will show the code. I created a contact before and now it makes another query with the same data directly to activeCampaign api: enter image description here

and i get expected result. But if made same request by firebase function i get properly status code but i don't see errors response from activeCampaign

FirebaseCloud function code:

const functions = require("firebase-functions");
const axios = require("axios");
const cors = require("cors")({ origin: true });

const addTagToContact = async (contactId: string, tagId: string) => {
try {
    await axios({
        method: "post",
        url: "https://xyz.api-us1.com/api/3/contactTags",
        headers: {
            "Api-Token": "api-token",
        },
        data: {
            contactTag: {
                contact: contactId,
                tag: tagId,
            },
        },
enter code here
    });
} catch (e) {
    console.error(e);
}
};

export const createNewContact = functions.https.onRequest((request: { body: any; }, response: { status: (arg0: number) => void; send: (arg0: { response?: unknown; status?: string; }) => void; }) => {
cors(request, response, async () => {
    const newContactData = request.body;
    if(!newContactData.email || !newContactData.fieldValues) {
        return response.send({
            response: 'No contact data provided'
        })
    } 

    try {
        const responseActiveCampaign = await axios({
            method: "post",
            url: "https://xyz.api-us1.com/api/3/contacts",
            headers: {
                "Api-Token": "api-token",
                "Content-Type": "application/json"
            },
            data: {
                contact: newContactData,
            },
        });
        console.log('response active campaign console log', responseActiveCampaign)
        await addTagToContact(responseActiveCampaign.data.contact.id, "1")
        return response.send({
            response: responseActiveCampaign.data
        })
    } catch (error) {
        console.error('catch error', error);
        response.status(500);
        response.send({
            response: error,
        });
    }
});
});

response from this query: enter image description here

How can i fix it? I would like to get error response from activeCampaign to use on my frontend

1

There are 1 best solutions below

0
Kamil On

the catch should be like this:

catch (error) {
    console.error('catch error', error);
    response.status(500);
    response.send({
        response: error.response.data,
    });
}