简体   繁体   English

react/axios — 无法通过 API 调用获取数据

[英]react/axios — not able to get data by API call

I am working on React first time, I am doing a API call in my react code.我第一次在 React 上工作,我正在我的 React 代码中调用 API。 I am following an example from net.我正在关注网络上的一个例子。 The example working perfectly.该示例完美运行。 And I am following same way and implemented my API call.我遵循相同的方式并实现了我的 API 调用。 API call is successful. API 调用成功。 but I am assigning the response to an object and printing it in the console, but my object printing as unknown.但我将响应分配给一个对象并在控制台中打印它,但我的对象打印为未知。

My code:我的代码:

export const getXFlowdata = async () => {
    try{
        const {data} = axios.get(xurl, { headers: headers });

        console.log('Data: ', data)
        console.log('Data Type: ',typeof data)
       
        return data;
 
    }catch(error) {
        throw error;
    }
}

Output:输出:

Data: undefined数据:未定义

Data Type: undefined数据类型:未定义

Example I fallowing:示例我休耕:

export const getPieData = async () => {
    try{
        const {data} = await axios.get(baseUrl);
        console.log('Data: ', data)
        console.log('Data Type: ',typeof data)
        return data;
    }catch(error){
        throw error;
    }
}

Output:输出:

Data: {confirmed: {…}, recovered: {…}, deaths: {…}, dailySummary:数据:{确认:{…},恢复:{…},死亡人数:{…},dailySummary:

Data Type: object数据类型:对象

You are getting a promise rather the data itself because you have not written await inside an async function and the promise does not have any property data because it is not resolved yet.您正在获得一个承诺而不是数据本身,因为您没有在异步函数中写入 await 并且承诺没有任何属性数据,因为它尚未解析。

  export const getXFlowdata = async () => {
    try{
        const {data} = await axios.get(xurl, { headers: headers });

        console.log('Data: ', data)
        console.log('Data Type: ',typeof data)
       
        return data;
 
    }catch(error) {
        throw error;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM