javascript - 使用 Node js 读取谷歌电子表格数据不起作用..?

标签 javascript node.js google-sheets-api

我正在使用postman来调用api。我正在尝试使用 Node js 读取 google 电子表格行。响应正在控制台上打印,但没有返回到 postman 。

index.js 文件

app.post('/myapi/getClientkey',async (req, res) => {
  var response = null;
  console.log("Inside myapi");
  try {
    response = await spreadsheet.getRecord();
  } catch(err){

  }
  res.send(response);
});

电子表格.js

var config = require('./config.json');
var GoogleSpreadsheet = require('google-spreadsheet');
var creds = {
  client_email: config.client_email,
  private_key: config.private_key
}
var doc = new GoogleSpreadsheet(config.GOOGLE_SHEET_ID)
var sheet = null;


exports.getRecord =  async function () {

  console.log('Inside - getRecord');
  var name = null;
  var jsonObj = {};
  try {
          doc.useServiceAccountAuth(creds, async function (err) {
            // Get all of the rows from the spreadsheet.
            await doc.getRows(1, async function (err, rows) {
                if(rows != null){
                  var oneRow = rows[0];
                  name = oneRow.name;
                  console.log("name :"+name);
                  jsonObj.client_name = name.toString();
                }
              console.log(jsonObj);  
            });
          }); 
   }catch(err){
      console.log("err :"+err);
  }
  return jsonObj;
};

如何等待 getRecord 函数返回响应

最佳答案

res.send(response); 移至 try block 内并阅读 how to return response from an async call .

此外,return jsonObj 应该位于 try block 内

关于javascript - 使用 Node js 读取谷歌电子表格数据不起作用..?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59752433/

相关文章:

google-api - 服务帐户是否被视为 Google Sheets API v4 使用限制中的用户?

python - 通过云功能访问 Google 表格 Python API 的身份验证问题

javascript - 根据 DIV 大小调整 iFrame 的大小

javascript - 在重置循环之前使 slider 中的最后一个图像暂停( slider 从头开始)

node.js - TypeError : assert. isNotEmpty 不是带有 chai 断言的函数

node.js - Google Sheet API,需要但未指定 'valueInputOption'

javascript - 如何获取 Jade 中动态生成的输入的值

javascript - ReactJS Prop 已更新,但字段未重新呈现

javascript - Node.js puppeteer - 如何从表中仅获取某些(过滤器)记录

javascript - MongoDB/Node.JS : Inserting documents in a loop - variables not updating?