【发布时间】: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