Why does Res.send return an empty object when console.log indicates it is not empty?

I am currently facing a challenge while using the Google Sheets API with Express, as I have limited experience with JavaScript. My goal is to pass a JSON object from Express to React, but for some reason, when I send the object, it appears empty on the frontend.

I have attempted to use res.body/res.data without success. Additionally, I have made sure to include as many awaits as possible to ensure that the object is fully loaded before sending it. However, nothing seems to resolve the issue. When trying to use res.json or res.send with just the response object, I encounter a circular structure conversion error to JSON. Below is the code snippet I am working with:

async function docShit() {
  // Initialize the sheet - doc ID is the lengthy ID in the sheets URL
  const doc = new GoogleSpreadsheet(
    " --SPREADSHEET ID-- "
  );

  // Initialize Auth - view https://theoephraim.github.io/node-google-spreadsheet/#/getting-started/authentication
  await doc.useServiceAccountAuth({
    client_email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
    private_key: process.env.GOOGLE_PRIVATE_KEY,
  });

  await doc.loadInfo(); 

  const sheet = doc.sheetsByTitle[--WORKSHEET TITLE--]; 
  const rows = await sheet.getRows();

  return rows;
}

app.get("/home", async (req, res) => {
  try {
    await docShit()
      .then((response) => {
        res.send(Promise.resolve(response)); 
      })
      .catch((err) => console.log(err));
  } catch (err) {
    console.error(err.message);
  }
});

Answer №1

Your code lacks the usage of res.send. Additionally, you are combining await and .then, which are typically used as alternatives to each other. Consider modifying your code as shown below:

app.get("/home", async (req, res, next) => {
  try {
    let response = await fetchData();
    console.log(response);
    
    // Determine which parts of the response to send if it is circular
    res.json(response.map(row => {
      return {id: row.id, cells: row.cells.map(cell => {
        return {id: cell.id, value: cell.value};
      })};
    });
  } catch (error) {
    console.error(error.message);
    next(error);
  }
});

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

What is causing the issue with dynamic special characters not functioning properly in my React router?

I am working with 3 components named App.js, SearchCategoryPage.js, and Home.js. However, when I click on the search icon, it does not navigate me to the search page. What could be the reason for this issue? App.js const outlet_id = useSelector((state) =& ...

Fetching all data from a SQLite database in a Listview using React Native

I have been utilizing the library found at https://github.com/andpor/react-native-sqlite-storage in my react native project. To retrieve a single row from the database, I use the following code: db.transaction((tx) => { tx.executeSql('SEL ...

The alpha value returned by gl.readPixels in Three.js will consistently be 255

Is there a way to retrieve pixel values from a threejs application? const gl = renderer.context; const currentFrame = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); // read image data from gl gl.readPixels(0, 0, gl.drawingBufferWidth ...

Identifying activity on a handheld device

I am currently working on a website and I have noticed that it doesn't work as well on mobile devices as it does on desktop. There are performance issues that need to be addressed. I've seen other websites redirecting users to a different page wh ...

Utilizing the JavaScript map method to structure API response data

Here is the JSON data I have: { "result": [{ "name": "a", "value": 20, "max": 100, "sale_value": [{ "no": 1, "name": "aaaaa", "price": 200 }, { "no": 2, ...

Creating a personalized news feed using getstream.io in Node.js - a step-by-step guide

const stream = require('getstream'); // Setting up a newsfeed stream using getstream const client = stream.connect( null, ); // Defining a feed for user1 var user1 = client.feed('user', 'user1'); // Adding a custom activity ...

Detecting collisions between two squares in an HTML5 canvas

class Snake { constructor() { this.x = 400; this.y = 400; this.width = 25; this.height = 25; } draw() { ctx.fillRect(this.x, this.y, this.width, this.height); } } let snake = new Snake(); class ...

Issue: Database not updating after input via AJAXExplanation: Despite submitting new data through AJAX, the

I've been struggling to display the UPDATED database on my initial html page after submitting new information. Despite successfully updating the database using AJAX, I can only see the outdated version. Any assistance in resolving this issue would be ...

Error occurs when attempting to read the 'map' properties of null because the JSON array is double nested

Within my code, I am attempting to access the URLs of two thumbnails in the JSON data below. Currently, I can only retrieve the information from the first array: <>{post.attributes.description}</> However, I am encountering difficulty retrievi ...

Ways to determine if an AngularJS modal is currently displayed

I am currently in the process of determining whether a modal is opened or closed. However, I keep encountering an error that says "cannot read property of open." To address this issue, I realize that I need to connect with $modal.open and retrieve the resu ...

Revive the JavaScript library for handling mouse wheel events

Utilizing the wheel-indicator JavaScript library, I am looking to revert the mouse wheel event back to its original state after it was initially set to preventDefault(). Despite attempting to use indicator.setOptions({preventMouse:"false"}) as suggested b ...

Exploring the world of Django and JSON POSTs in the realm of Google API mania

Project Overview I am currently developing an application aimed at assisting users in finding rides. My tech stack includes Django, Python 2.7, and integration with Google Maps and Directions APIs. Within a specific view, I present a map where users can ...

Form an item using an array

Is there a way to efficiently convert this array into a map? Here is how the array looks: var array = [{ "id" : 123 }, { "id" : 456 }, { "id" : 789 }]; The desired output should be: var result = { "123": { id: 123 } , "456": { id: 456 } , ...

Ensuring Filesize Verification Prior to Upload on Internet Explorer Using Javascript

Can JavaScript be used to verify a file's size before it is uploaded to the server at the client side? This application is developed using EXTJS and Java and is limited to Internet Explorer 7 on Windows XP machines. ActiveX cannot be used. The workf ...

Guide to installing angular-ui-bootstrap through npm in angularjs application

My goal is to incorporate angular-ui-bootstrap into my project using the following steps: 1. npm install angular-ui-bootstrap 2. import uiBootstrap from 'angular-ui-bootstrap'; 3. angular.module('app', [      uiBootstrap    ]) I ...

Tips for positioning a modal in the center specifically for zoomed-in mobile devices

I created a modal that uses the following function to center itself: center: function() { var top=Math.max($window.height() - $modal.outerHeight(),0) / 2; var left=Math.max($window.width() - $modal.outerWidth(),0) / 2; $modal.css({ ...

Converting timestamps: Retrieve day, date, hour, minutes, etc. without utilizing the "new Date()" function

Currently developing a web-app and faced with the challenge of displaying items in a list correctly. I am working on converting the timestamp attached to each item into a readable format. For instance, 1475842129770 is transformed into Friday, 07.09.2016 ...

Exclude basic authentication for a specific route

Using node, express and connect for a simple app with basic HTTP auth implemented. The code snippet below shows part of the implementation: var express = require('express'), connect = require('connect'); app.configure = function(){ ...

Determine if an option is chosen in multiple select elements using Vanilla JavaScript

In order to determine if a checkbox is checked, we use the following code: let isChecked = event.target.checked But what about multiple select options like the example below? <select name="books[]" multiple> <option value="A">A</option& ...

Node.js client connecting with Elasticsearch encounters issues with ECONNRESET and running out of heap memory space

tag, I have a script that scans through a set of log files, each averaging around 15 MB. The script extracts specific data fields from these logs and then sends a bulk request to elasticsearch. The code snippet is as follows: // locate all files with .log ...