Error: Unable to encode data into JSON format encountered while using Firebase serverless functions

I am currently working on deploying an API for my application. However, when using the following code snippet, I encountered an unhandled error stating "Error: Data cannot be encoded in JSON."

const functions = require("firebase-functions");
const axios = require("axios");
exports.getDatas = functions.https.onCall(async (d)=>{
  functions.logger.log(d["name"]);
  cname = d["name"];
  ts1=d["ts1"];
  ts2=d["ts2"];
  const data =  await axios.get(
    "https://api.coingecko.com/api/v3/coins/" +
    cname +
      "/market_chart/range?vs_currency=usd&from=" +
      ts1 +
      "&to=" +
      ts2,
  );
  functions.logger.log(data);
  return {data: data};
});

The error log generated is as follows:

Unhandled error Error: Data cannot be encoded in JSON: function httpAdapter(config) {
// The rest of the error log...

The first logger correctly logs the parameter passed, while the second logger that logs the data has a format like this:

...[{"api.coingecko.com:443::::::::::::::::::"}]
// The rest of the data log...

Although the code successfully logs the data, I'm facing challenges with returning it at the end. Can someone provide assistance?

Answer №1

It seems like the issue lies in trying to return the entire Axios response, which cannot be serialized as JSON due to circular references.

To resolve this, simply return the response data instead. Additionally, consider simplifying and making your URL construction safer by utilizing the params option.

exports.getDatas = functions.https.onCall(async ({ name, ts1, ts2 }) => {
  functions.logger.log(name);
  //    👇 note the destructure here
  const { data } = await axios.get(
    `https://api.coingecko.com/api/v3/coins/${encodeURIComponent(name)}/market_chart/range`,
     {
      params: {
        vs_currency: "usd",
        from: ts1,
        to: ts2,
      }
    }
  );
  functions.logger.log(data);
  return { data };
});

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

Invoke the callback function before executing the next function

There is a function that calls an API: const response = fetch(APIfunctonName, { method: "POST", body: JSON.stringify(searchRequest), headers: { "Content-type": "application/json; charset=UTF-8", }, }) ...

Trouble with ng-repeat when working with nested json data

Check out this app demo: http://jsfiddle.net/TR4WC/2/ I feel like I might be overlooking something. I had to loop twice to access the 2nd array. <li ng-repeat="order in orders"> <span ng-repeat="sales in order.sales> {{sales.sales ...

Steps to retrieve data (token) from developer tools and incorporate it into a fetch Post request

Is there a simple way to extract data using dev tools and insert it into a fetch request? I am trying to make a POST request through the console, but I am struggling to correctly copy a token. I attempted to use querySelector but instead of finding the t ...

How to detect a click event in any area of an Angular2

Hey there, I'm new to typescript and angular 2 and I've encountered an error in my code. Can someone lend me a hand in fixing this? import { Component, HostListener } from '@angular/core' export class TooltipComponent { public sh ...

What is the method to determine the size of a file in Node.js?

Have you ever wondered how to accurately determine the size of a file uploaded by a user? Well, I have an app that can do just that. The code for this innovative tool is provided below: Here is the snippet from server.js: var express = require('expr ...

How can I transfer data to a different component in Angular 11 that is not directly related?

Within the home component, there is a line that reads ...<app-root [message]="hii"> which opens the app-root component. The app-root component has an @input and {{message}} in the HTML is functioning properly. However, instead of opening t ...

Change the default values for grid column configurations in Ext JS globally

The Ext.grid.column.Column class contains the following configurations: draggable (Default: true) sortable (Default: true) menuDisabled (Default: false) Is there a way to globally change the default values of these configurations for all grid columns i ...

Retrieving data in [slug].js using Reactjs

I am currently working on a project in Reactjs utilizing the "nextjs" framework. I have successfully managed to retrieve data (specific blog details) based on the slug([slug.js]). However, I now need to display data from all other blogs within the same c ...

What is the reason for the request body being undefined?

I have a JavaScript file named index.js that contains: const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const db = require('./db'); const movieRouter = re ...

Issues with TypeScript "Compile on save" functionality in Visual Studio 2015

The feature of "Compile on save" is not functioning properly for me since I upgraded to Visual Studio 2015. Even though the status bar at the bottom of the IDE shows Output(s) generated successfully after I make changes to a .ts file and save it, the resul ...

Can saving data within a mongoose pre-save hook initiate a continuous loop?

Currently, I am developing an API for a forum system which includes functionalities for users, forums, and posts. In my MongoDB Database, there is a 'categories' collection where each category acts as a container for a group of forums. Each categ ...

At times, the loading image fails to appear on Ajax

Take a look at my code below: function apply_image_effect(){ $.ajax({ url: "image/image.php", global: false, type: "POST", data: ({my_color:encodeURIComponent($('#my_color').val()),my_size:$('#my_size&apos ...

Experiencing a hiccup in React while attempting to play an mp3 file

My project includes the following code snippet, with an example mp3 file and npm package: https://www.npmjs.com/package/react-sound import React from 'react'; import Sound from 'react-sound'; class CustomSound extends React.Component ...

Having trouble retrieving the $_SESSION variable accurately from AngularJS

I am working with angularjs and need to retrieve a php session variable. I have created a php file named session.php with the following content: $_SESSION['phone'] = '55551864'; return json_encode($_SESSION['phone']); In my ...

The response from a post request in Reactjs using axios is coming back empty

When working on my Reactjs app, I am using axios.post() to edit a mysql database on the backend. The data is successfully sent through the post request to the backend. However, I am facing an issue where I need to determine when the post request has finish ...

What is the best way to automatically scroll to the bottom of a modal after making a request and

I've been faced with a challenge regarding an online chat widget. My goal is to automatically scroll the widget down to display the latest message when a specific chat is opened. Despite using an async function, I encountered difficulties in achieving ...

Vue.js - The prop "src" is invalid as the type check has failed. The expected type should be either a string or an object, but a

I am currently working on integrating an image into my Firebase's Firestore and Storage, and then displaying it on a v-card component. Here is the code for my v-card: <v-row> <v-col cols="3" v-for="massage in massages" ...

What is the best way to ensure TypeScript recognizes a variable as a specific type throughout the code?

Due to compatibility issues with Internet Explorer, I find myself needing to create a custom Error that must be validated using the constructor. customError instanceof CustomError; // false customError.constructor === CustomError; // true But how can I m ...

Looking to efficiently output information generated within a headless browser in node.js

Is there a way to print out data created inside a Node.js running headless browser if console.log('Text') isn't working? For example: const pup = require('puppeteer'); const chrom = await pup.launch({headless:'new'}); ...

Not every time you call the AngularJS run method does it actually execute

Working on a simple Angular app, I wanted to implement a user login check and redirection. However, I encountered an issue where accessing the home page from the form site resulted in inconsistent behavior - sometimes redirecting and other times showing ...