如何从异步提取请求中获取响应? (节点提取)

时间:2020-09-09 08:18:36

标签: javascript node.js httprequest node-fetch

我正在使用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)

1 个答案:

答案 0 :(得分:3)

您需要使用await关键字,text()是一个承诺。

const response = await res.text();
console.log(response);
相关问题