【问题标题】:How to get a response from async fetch request? (node-tetch)如何从异步获取请求中获得响应? (node-tetch)
【发布时间】:2020-12-27 15:27:06
【问题描述】:

我正在使用node-fetch 进行简单的 HTTP POST 请求,但我无法得到响应? 我收到以下错误:

(node:7200) UnhandledPromiseRejectionWarning: FetchError: invalid json response
body at url reason: Unexpected token А in JSON at position 0

当这个console.log(res.json()); 代码运行时。公平地说,这个 URL 返回一个单行字符串作为响应。也许console.log(res.text()); 应该适合我?

没有:res.text() = [object Promise]

我如何得到响应?我的代码:

const fetch = require("node-fetch");
var inspect = require('eyes').inspector({maxLength: false})
async function postLendingApplication(name) {
    try {
      console.log("Processing POST Loan.");
    
        var data = {
            "name" : name
        }
        var auth = Buffer.from("login:password").toString('base64')
        console.dir('data '+JSON.stringify(data));
        console.dir('auth '+auth);
      // the await eliminates the need for .then
      const res = await fetch("url.com", {
          method: "POST",
          headers: {
            'Content-Type': 'application/json',
            'Authorization': "Basic "+auth
          },
          body: JSON.stringify(data)
      })
     console.log("res.text() = "+res.text());
     //console.log(res.json());
      return res;
   }
   catch(err) { 

    throw err
    }
}

var result= postLendingApplication("00025003")
console.log(result)

【问题讨论】:

  • res.text() 返回 Promise 就像 res.json() 一样,您将其记录到控制台,而无需等待 Promise 解决。

标签: javascript node.js httprequest node-fetch


【解决方案1】:

你需要使用await关键字,text()是一个promise。

const response = await res.text();
console.log(response);

【讨论】:

  • 感谢这对我有用。但我有最后两行:var result = postLendingApplication("00025003")console.log('la la la '+result) 返回以下内容:la la la [object Promise] 使用此方法的全部原因是从异步 HTTP 请求中获取响应。现在它返回这个?
  • 调用函数时只需使用await关键字:var result = await postLendingApplication("00025003")。这是相同的概念,您正在分配“结果”承诺,而不是等待承诺解决,然后分配承诺解决的值。
  • 是的,我试过了,但现在我得到了SyntaxError: await is only valid in async function
  • 我认为您应该阅读承诺,因为我认为您缺少一些核心理解(不是批评,只是建议)。无论如何,如果您不在异步函数中调用它,只需执行以下操作:postLendingApplication("00025003").then((res) => { console.log(res); })。您将看到记录的结果。简而言之,promise 必须在某个时候得到解决,才能得到想要的结果。
猜你喜欢
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-25
  • 1970-01-01
  • 1970-01-01
  • 2013-04-02
  • 1970-01-01
相关资源
最近更新 更多