我正在使用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)
答案 0 :(得分:3)
您需要使用await
关键字,text()是一个承诺。
const response = await res.text();
console.log(response);