[英]NodeJS Axios response undefined on console.log API
I try to make this code work.我试着让这段代码工作。
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
Response type of the API: API的响应类型:
"discord":{"Category":"activation","Qty":1542,"Price":1}
"vkontakte":{"Category":"activation","Qty":133,"Price":21}
I get it ''undefined''.我得到它“未定义”。 Running on NodeJS.在 NodeJS 上运行。
axios return promise 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))
You can chain a then method as axios returns promise.您可以在 axios 返回 promise 时链接 then 方法。 you can also chain a catch method to catch potential errors.您还可以链接一个 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);
});
hope this helps.希望这可以帮助。 GOOD LUCK :)祝你好运 :)
Axios Returns a promise. Axios 返回一个承诺。 You can look at the documentation here您可以在此处查看文档
You can either use await to wait for the response in that case you should use a try catch block to make sure you take care of the errors from your discord Endpoint.您可以使用 await 等待响应,在这种情况下,您应该使用 try catch 块来确保处理来自不和谐端点的错误。 This is a good read on error handling for asnyc/wait ( here ) Like @arshpreet suggested这是关于 asnyc/wait 的错误处理的好读物( 这里)就像@arshpreet 建议的那样
(async ()=>{
try{
let bodyapi = await axios.get('there's my api')
console.log(bodyapi.data) // response
} catch(error){
console.error(error)
}
})()
Or you can do it then and catch to take care of the errors.或者你可以这样做并捕获以处理错误。 just like waleed has mentioned.就像瓦利德提到的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.