【问题标题】:My module.exports return as [object Object]我的 module.exports 返回为 [object Object]
【发布时间】:2020-05-24 14:08:40
【问题描述】:

我使用 API 来获取一些我需要的信息。

let bodyapi = await axios.get(`www.example.com`)

然后我像这样导出我需要的信息:

const number = bodyapi.data.slice(-11);

module.exports = number

然后我用const number = require('./myapp.js') 在我的实际文件上运行它(像往常一样)。
但问题是当我阅读它时,它返回[object Object]

const number = require('./myapp.js')
sleep(5000) // It's a timeout function I've set, ignore it, it's just so I don't run the code too fast since it uses API''
console.log("Your ID: " + number) //Here is where it reads as [object Object]

控制台结果:

Your ID: [object Object]


我的问题是:我该如何修复它,所以它会读取我需要它读取的内容? bodyapi 被制成一个“异步”函数。我使用Axios 读取api。


如果您需要更多信息,请在 cmets 中告诉我,以便我编辑这篇文章。感谢您的宝贵时间!

【问题讨论】:

  • 在导出之前确保console.log(number) 看起来像你想要的那样。

标签: javascript node.js api axios export


【解决方案1】:

问题出在控制台日志上。您正在对您的数字对象进行字符串化: 请尝试以下操作:

const number = require('./myapp.js')
sleep(5000) // It's a timeout function I've set, ignore it, it's just so I don't run the code too fast since it uses API''
console.log("Your ID: ", number) //

【讨论】:

  • 你好。谢谢您的答复。现在我得到“{}”作为一个值。知道为什么吗?
  • @Lmao123 你的对象是空的。您可以通过控制台登录 myapp.js 模块进行检查。
  • 好的,谢谢。我会检查一下,看看有什么问题。
【解决方案2】:

我认为这不是从异步函数导出响应并将它们与睡眠一起使用的正确方法。您应该考虑像这样导出函数

async function getResponse() {

  let bodyapi = await axios.get(`www.example.com`);
  const number = bodyapi.data.slice(-11);
  return number;
}

module.exports = getResponse;

那你想用在哪里,就可以这样用

const getResponse = require('./myapp.js');

getResponse()
  .then(number => console.log(number));

或者使用异步/等待


const getResponse = require('./myapp.js');

(async() => {
   const number = await getResponse();
   console.log(number);
})();

将其记录为 [object object]。如果你尝试用字符串连接一个对象,你会看到这种行为。

【讨论】:

  • 我都做了,使用.then,我得到的数字是''未定义''。使用 async 时出现错误,因为我已经在我的主脚本上使用了 async for puppeteer。
猜你喜欢
  • 1970-01-01
  • 2011-07-13
  • 2013-09-13
  • 2015-01-24
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多