I'm using node-fetch
for a simple HTTP POST request but I'm unable to get a response from it?
I'm getting follwoing error:
(node:7200) UnhandledPromiseRejectionWarning: FetchError: invalid json response
body at url reason: Unexpected token А in JSON at position 0
when this console.log(res.json());
code runs. Fair, this URL returns a single line string as response. Maybe console.log(res.text());
should work for me?
Nope: res.text() = [object Promise]
How do I get response from this? My code:
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)
You need to use the await
keyword, text() is a promise.
const response = await res.text();
console.log(response);