如何从node-fetch异步POST请求中获取响应?
解决node-fetch获取响应的问题
我来帮你梳理下问题所在,其实都是异步操作的细节没处理好:
1. res.text() 返回Promise,必须用await获取实际内容
你看到的[object Promise]是因为res.text()是异步方法,它不会直接返回字符串,而是返回一个Promise对象。要拿到真实的响应文本,必须加上await:
const textResponse = await res.text(); console.log("res.text() = " + textResponse);
2. 调用async函数时要处理它返回的Promise
你的postLendingApplication是async函数,所以直接调用var result= postLendingApplication("00025003")得到的是一个Promise,不是最终的响应结果。你需要用await(得放在async环境里)或者.then()来处理:
比如用立即执行函数创建async环境:
(async () => { var result = await postLendingApplication("00025003"); console.log(result); })();
或者用.then()链式调用:
postLendingApplication("00025003") .then(result => console.log(result)) .catch(err => console.error(err));
3. 关于res.json()报错的原因
这个报错逻辑很明确:接口返回的是单行字符串,不是合法的JSON格式,所以用json()方法解析肯定会失败。你选择用res.text()是完全正确的,只要处理好异步逻辑就行。
修改后的完整代码
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); const res = await fetch("url.com", { method: "POST", headers: { 'Content-Type': 'application/json', 'Authorization': "Basic "+auth }, body: JSON.stringify(data) }) // 用await获取text响应内容 const textResponse = await res.text(); console.log("res.text() = " + textResponse); // 如果需要返回响应文本,就返回textResponse而非res对象 return textResponse; } catch(err) { console.error("请求出错:", err); throw err } } // 正确调用async函数 (async () => { try { var result = await postLendingApplication("00025003"); console.log("最终结果:", result); } catch (err) { console.error("处理失败:", err); } })();
另外补充一点:如果后续接口可能切换返回格式,可以先判断响应的Content-Type头,再决定用json()还是text(),不过根据你的描述,接口固定返回单行字符串,直接用text()就足够了。
内容的提问来源于stack exchange,提问作者J. Doe
相关产品推荐
相关产品推荐

