如何从异步获取请求中获取响应? (节点技术)
How to get a response from async fetch request? (node-tetch)
我正在使用 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 returns 单行字符串作为响应。也许 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()是一个promise。
const response = await res.text();
console.log(response);
我正在使用 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 returns 单行字符串作为响应。也许 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()是一个promise。
const response = await res.text();
console.log(response);