我正在尝试使用带有 async/await 的请求模块在一个文件中进行 api 调用,并使用 return 将响应发送到另一个文件中的另一个变量以供使用。下面是代码示例:
文件 1:
async returnResponse(body) {
let options = {
url: url,
form: body,
method: 'POST',
headers: header,
json: true
};
return await request(options, function (error, response) {
console.log("file 1 resp", response.body);
return response.body;
});
}
文件 2:
return new Promise(async (resolve, reject) => {
try {
const resp = await this.returnResponse(body);
console.log('file 2 resp: ', resp);
resolve(resp.body);
} catch (err) {
reject(err);
}
});
在文件 1 中,请求函数中的控制台日志显示正确的信息,但文件 2 中的控制台日志显示如下请求信息
Request {
_events: [Object: null prototype] {
error: [Function: bound ],
complete: [Function: bound ],
pipe: [Function]
},
_eventsCount: 3,
_maxListeners: undefined,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
accept: 'application/json',
'content-length': 576
},
callback: [Function],
readable: true,
writable: true,
explicitMethod: true,...
我知道我可能在这里遗漏了一些小东西,但我已经坚持了将近两天,如果我能得到任何帮助,我将不胜感激。
旁注:我尝试了 Needle 和 axios,但我无法使用“Content-Type”正确格式化正文:“application/x-www-form-urlencoded”