如何解决如何从异步提取请求中获取响应? 节点提取
我正在使用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)
解决方法
您需要使用await
关键字,text()是一个承诺。
const response = await res.text();
console.log(response);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。