在 NodeJS 中获取和发布文本 [英] Fetch and post text in NodeJS
问题描述
我正在尝试从只返回一串文本的 API 中获取文本((此处)) 并且在回复中遇到麻烦.发布时,它显示为 [object Response]
,并且 console.log
没有显示我想要的文本.
I'm trying to grab text from an API that only returns a string of text ((here)) and having troubles throwing that out in a response. When posting, it comes out as [object Response]
, and the console.log
doesn't show the text I want out of it.
我使用的代码:
fetch('http://taskinoz.com/gdq/api').then(
function(response) {
console.log(response);
throttledSendMessage(channel, response);
return response;
})
.catch(function(error) {
throttledSendMessage(channel, "An error has occured");
})
日志可以在在这里找到
感谢与我一起寻找,找不到解决方案:/
Thanks for looking with me, couldn't find a solution :/
推荐答案
问题可能出在 node.js 的异步行为上.您可以在此处阅读更多内容
另外,我假设您使用 this 包在 node.js 中进行获取请求.
并假设 throttledSendMessage
函数是同步的.
关于您的问题,只需尝试重写代码以使用 async/await 以获得更清晰的解决方案.
Probably the problem is in async behavior of node.js. You can read more here
Also, I'm assume you use this package to make fetch request in node.js.
And assume that throttledSendMessage
function is synchronous.
About your problem, just try to rewrite co de to use async/await for cleaner solution.
// We'll use IIFE function
(async () => {
const fetchResult = await fetch('http://taskinoz.com/gdq/api')
// Here fetch return the promise, so we need to await it again and parse according to our needs. So, the result code would be this
const data = await fetchResult.text();
throttledSendMessage(channel, data);
return data;
})()
这篇关于在 NodeJS 中获取和发布文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!