Ошибка «Преобразование круговой структуры в JSON», несмотря на то, что функции выполняются правильно - PullRequest
0 голосов
/ 07 ноября 2019

Я получаю следующую ошибку:

TypeError: Преобразование круговой структуры в JSON

 at JSON.stringify (<anonymous>)
 at stringify (/usr/local/lib/node_modules/firebase-tools/node_modules/express/lib/response.js:1123:12)
 at ServerResponse.json (/usr/local/lib/node_modules/firebase-tools/node_modules/express/lib/response.js:260:14)
 at cors (/Users/landing-page-backend/functions/zohoCrmHook.js:45:43)
 at process._tickCallback (internal/process/next_tick.js:68:7)

для ответа HTTP в моей функции createLead,несмотря на тот факт, что функция выполняется правильно и выполняет то, что должна делать (то есть создать запись в моей CRM).

Я указал в следующем коде, где происходит ошибка:

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

const clientId = functions.config().zoho.client_id;
const clientSecret = functions.config().zoho.client_secret;
const refreshToken = functions.config().zoho.refresh_token;
const baseURL = 'https://accounts.zoho.com';



module.exports = (req, res) => {
    cors(req, res, async () => {        
        const newLead = {
            'data': [
            {
                'Email': String(req.body.email),
                'Last_Name': String(req.body.lastName),
                'First_Name': String(req.body.firstName),
            }
            ],
            'trigger': [
                'approval',
                'workflow',
                'blueprint'
            ]
        };

        const { data } = await getAccessToken();
        const accessToken = data.access_token;

        const leads = await getLeads(accessToken);
        const result = checkLeads(leads.data.data, newLead.data[0].Email);

        if (result.length < 1) {
            try {
                return res.json(await createLead(accessToken, newLead)); // this is where the error occurs
            } catch (e) {
                console.log(e); 
            }
        } else {
            return res.json({ message: 'Lead already in CRM' })
        }
    })
}

function getAccessToken () {
    const url = `https://accounts.zoho.com/oauth/v2/token?refresh_token=${refreshToken}&client_id=${clientId}&client_secret=${clientSecret}&grant_type=refresh_token`;

    return new Promise((resolve, reject) => {
      axios.post(url)
        .then((response) => {
          return resolve(response);
        })
        .catch(e => console.log("getAccessToken error", e))
    });
}

function getLeads(token) {
    const url = 'https://www.zohoapis.com/crm/v2/Leads';

    return new Promise((resolve, reject) => {
      axios.get(url, {
        headers: {
          'Authorization': `Zoho-oauthtoken ${token}`
        }
      })
        .then((response) => {
          return resolve(response);
        })
        .catch(e => console.log("getLeads error", e))
    })
}

function createLead(token, lead) {
    const url = 'https://www.zohoapis.com/crm/v2/Leads';

    return new Promise((resolve, reject) => {
        const data = JSON.stringify(lead);
        axios.post(url, data, {
            headers: {
                'Authorization': `Zoho-oauthtoken ${token}`
            }
        })
        .then((response) => {
            console.log("response in createLead", response)
            return resolve(response);
        })
        .catch(e => reject(e))
    })
}

function checkLeads(leads, currentLead) {
    return leads.filter(lead => lead.Email === currentLead)
}

Console.logging все параметры указывают, что они не являются проблемой. Конфигурация API Zoho также не является проблемой, учитывая тот факт, что записи правильно вносятся в CRM. Я предполагаю, что это будет связано с ответом HTTP в формате JSON.

1 Ответ

0 голосов
/ 07 ноября 2019

Вы пытаетесь конвертировать promise в JSON, не собираясь работать. Ваша createLead функция возвращает promise, а не JSON. promise является «круглым объектом».

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...