【问题标题】:NodeJS Axios response undefined on console.log API在 console.log API 上未定义 NodeJS Axios 响应
【发布时间】:2020-05-14 17:48:33
【问题描述】:

我试图让这段代码工作。

const axios = require('axios');
let bodyapi = axios.get('there's my api')
console.log(bodyapi.data) <- undefined
let body = bodyapi.data
console.log(body.discord) <- couldn't get parameter ''discord'' of undefined

API的响应类型:

"discord":{"Category":"activation","Qty":1542,"Price":1}
"vkontakte":{"Category":"activation","Qty":133,"Price":21}

我明白了''未定义''。在 NodeJS 上运行。

【问题讨论】:

    标签: javascript node.js api axios http-get


    【解决方案1】:

    axios 返回承诺

    const axios = require('axios');
    
    // use async await 
    (async ()=>{
    let bodyapi = await axios.get('there's my api')
    console.log(bodyapi.data) // response
    })()
    
    // other way
    axios.get('there's my api').then(data=> console.log(data))
    

    【讨论】:

      【解决方案2】:

      您可以在 axios 返回 promise 时链接 then 方法。 您还可以链接一个 catch 方法来捕获潜在的错误。

      const axios = require('axios');
      axios.get('there's my api').then(bodyapi => {
      console.log(bodyapi.data) 
      let body = bodyapi.data
      console.log(body.discord)
      }).catch(error => {
      console.log(error);
      });
      

      希望这会有所帮助。祝你好运:)

      【讨论】:

        【解决方案3】:

        Axios 返回一个承诺。可以看文档here

        您可以使用 await 来等待响应,在这种情况下,您应该使用 try catch 块来确保您处理来自不和谐端点的错误。这是关于 asnyc/wait 错误处理的好读物 (here) 就像@arshpreet 建议的那样

        (async ()=>{
        try{
        
          let bodyapi = await axios.get('there's my api')
           console.log(bodyapi.data) // response
          } catch(error){
             console.error(error)
          }
        })()
        

        或者你也可以这样做,然后捕获以处理错误。 就像waeed提到的那样。

        【讨论】:

          猜你喜欢
          • 2021-07-05
          • 2021-05-26
          • 1970-01-01
          • 1970-01-01
          • 2021-11-02
          • 2020-07-03
          • 1970-01-01
          • 1970-01-01
          • 2018-09-27
          相关资源
          最近更新 更多