javascript - Axios GET 请求返回 [object Promise]
问题描述
我目前正在尝试使用 axios.get 在 TypeScript 中获取数据:
try {
const resp = axios.get("http://localhost:8080/getdata").then(response => response.data)
return resp
// return "<img src=\"" + resp + "\"></div>"
} catch (exception) {
console.log("Error")
}
当我返回 resp 时,它会返回正确的响应(例如 data:image/png;base64 ...),但是,当我返回它时,<img src="resp">
它会返回 [object Promise]。有任何想法吗?
解决方案
试试 async/await 方法。
async function yourMethodName() {
try {
const response = await axios.get("http://localhost:8080/getdata");
return `<img src="${response.data}">`;
} catch(e) {
console.log(e);
}
}
或者,您可以简单地使用回调方法。
axios.get("http://localhost:8080/getdata").then((response) => { console.log(response); });
您的逻辑需要在回调中运行。
如果您想了解有关 Promises 的更多信息,这将有所帮助。它使用 fetch API 而不是 AXIOS,但它是相似的。
推荐阅读
- reactjs - Dragula拖动不能很好地识别dropzones
- haskell - 自定义高阶函数调用在约束错误中给出非类型变量参数
- django - Django将对象信息获取到方法而无需重新输入
- c++ - 复杂情况的C++比较器传参问题
- javascript - Chrome 中的回调执行时间与预期不符
- javascript - 如何开始使用 Webpack
- javascript - 如何使用 Tampermonkey 或 Stylebot 自动更改“显示条目”值?
- nativescript - 从当前 Java 上下文调用方法
- python - 使用莱布尼茨公式计算 pi 而无需导入任何东西
- c# - 为什么这会删除所有其他复选框?