在NodeJS中获取和发布文本 [英] Fetch and post text in NodeJS

查看:61
本文介绍了在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的异步行为中.您可以在此处了解更多信息
另外,我假设您使用包在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆