Axios GET 请求返回 [object Promise]

时间:2021-06-17 07:01:30

标签: javascript http axios get request

我目前正在尝试使用 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]。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

试试异步/等待方法。

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); });

您的逻辑需要在回调中运行。
如果您想了解有关 Promise 的更多信息,this 会有所帮助。它使用 fetch API 而不是 AXIOS,但它是相似的。

答案 1 :(得分:-1)

[object Promise] 是当程序还没有完成它正在做的事情时返回的内容。要从中获取数据,您需要解决承诺。

尝试用以下代码替换 try 语句中的代码:

const resp = axios.get("http://localhost:8080/getdata).then(response => response.data");
var promise = Promise.resolve(resp);

promise.then(function(value){

    return `<img src=" ${value} "></div>`;

});
相关问题