【问题标题】:Fetch and post text in NodeJS在 NodeJS 中获取和发布文本
【发布时间】:2019-09-04 16:14:47
【问题描述】:

我正在尝试从仅返回一串文本 ((here)) 的 API 中获取文本,并且在响应中将其抛出时遇到了麻烦。发布时,它显示为[object Response],而console.log 没有显示我想要的文字。

我正在使用的代码:

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");
  })

日志可以是found here

感谢您与我一起寻找解决方案:/

【问题讨论】:

    标签: node.js api fetch


    【解决方案1】:

    我认为因为fetch 返回一个Response,您需要调用Response 上的函数之一才能获取正文的文本。这是一个例子:

    fetch('https://github.com/')
      .then(res => res.text())
      .then(body => console.log(body));
    

    【讨论】:

      【解决方案2】:

      问题可能在于 node.js 的异步行为。你可以阅读更多here
      另外,我假设您使用 this 包在 node.js 中发出 fetch 请求。
      并假设throttledSendMessage 函数是同步的。

      关于您的问题,只需尝试重写代码以使用 async/await 以获得更简洁的解决方案。

      // 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;
      })()
      

      【讨论】:

      • 这个问题的答案与 Node 中的异步行为完全无关,与 fetch 返回响应对象而不是原始响应数据这一事实有关。
      • nodejs 本身不支持获取。上面的代码可以在现代浏览器中运行,如果它已经被 polyfill,也可以在 node 中运行,但没有原生 fetch。检查 node.green 以获取兼容语言功能列表和本机 API 的节点文档。
      • @FishPudding,请仔细阅读我的回答。我已经提到了运行此代码所需的包。带有 npm 包的链接。
      【解决方案3】:

      Fetch 在 nodejs 中不可用,你可以使用 node-fetch https://www.npmjs.com/package/node-fetch ,或者你可以使用这个 fetch 函数:

      const https = require('https');
      const http = require('http');
      
      function fetch(url, options = {}) {
        return new Promise((resolve, reject) => {
          if (!url) return reject(new Error('Url is required'));
      
          const { body, method = 'GET', ...restOptions } = options;
          const client = url.startsWith('https') ? https : http;
      
          const request = client.request(url, { method, ...restOptions }, (res) => {
            let chunks = '';
      
            res.setEncoding('utf8');
      
            res.on('data', (chunk) => {
              chunks += chunk;
            });
      
            res.on('end', () => {
              resolve({ statusCode: res.statusCode, body: chunks });
            });
          });
      
          request.on('error', (err) => {
            reject(err);
          });
      
          if (body) {
            request.setHeader('Content-Length', body.length);
            request.write(body);
          }
      
          request.end();
        });
      }
      
      module.exports = fetch;
      

      你可以在你的代码中这样使用它:

        const result = await fetch(
          `https://YOUR_URL`,
          {
            method: 'PUT',
            body: JSON.stringify({ test: 'This is just a test', prio: 1 }),
          },
        );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-31
        相关资源
        最近更新 更多