首页 > 解决方案 > 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]。有任何想法吗?

标签: javascripthttpaxiosgetrequest

解决方案


试试 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,但它是相似的。


推荐阅读