node.js - 如何从 .then 块返回响应?
问题描述
我有一个使用 Axios 库进行 HTTP 调用的方法,
HTTP 工作正常,但是我无法从 .then 块返回数据,
以下是我的方法 -
module.exports.postAPI = async (url, headers, data) => {
console.log("URL => ", url);
console.log("Payload => ", headers);
console.log("Data => ", data);
await axios({ method: 'POST', url: url, headers: headers, data: data })
.then((response) => {
console.log("POST API Call Successful \n");
console.log("POST Response => \n", response.data);
return response.data;
})
.catch((error) => {
console.log("POST API Call Unsuccessful \n", error,"\n");
return error;
});
}
调用 postAPI -
let test = async () => {
let url = 'someURL';
let headers = {
"Content-Type": "application/json"
};
let data = {
"someKey": "someValue"
};
let response = await commonUtil.postAPI(url, headers, data);
console.log("UTIL Response => \n", response);
}
POST API Call Successful and POST Response => and response.data
正在打印,
但数据没有返回给调用函数。
解决方案
使用 Async/await 或 Promise
异步/等待
module.exports.postAPI = async (url, headers, data) => {
console.log("URL => ", url);
console.log("Payload => ", headers);
console.log("Data => ", data);
try{
let response=await axios.post(url,data, {headers: headers} )
console.log("POST API Call Successful \n");
console.log("POST Response => \n", response.data);
return response.data;
}
catch(err){
console.log("POST API Call Unsuccessful \n", err,"\n");
return err
}
}
承诺
module.exports.postAPI = (url, headers, data) => {
console.log("URL => ", url);
console.log("Payload => ", headers);
console.log("Data => ", data);
axios.post(url,data, {headers: headers} )
.then((response) => {
console.log("POST API Call Successful \n");
console.log("POST Response => \n", response.data);
return response.data;
})
.catch((error) => {
console.log("POST API Call Unsuccessful \n", error,"\n");
return error;
});
}
推荐阅读
- ios - 为什么 UIVisualEffectView 在 SwiftUI 上下文菜单中不起作用?
- python - 如何在 Firebase 云功能中安装 TensorFlow
- spring-data - 如何在 Spring Data / Webflux 中使用可选属性
- shell - 为什么 conda 没有在这个 shell 脚本中激活我的环境?
- c++ - C ++:使用使用其默认构造函数的临时对象进行初始化声明函数原型而不是变量
- c# - 如何在 DirectShow.Net 中访问网络摄像头的电力线补偿和背光补偿设置
- c# - 如果在 MVC Core 3.1 中使用 asp-for 属性,则在 POST 之后不设置该值
- compilation - 编译会使 SSD 降级多少?
- laravel - 如何在单个查询中找到多列总和的总和
- php - Laravel:如何在 web.php 文件中返回路由名称