我有一个问题,我过去几天一直与我的朋友Google试图回答。这是我当前正在处理的项目中的代码,我正在尝试与两个API交互。
您在这里看到的是使用GOT库格式调用第一个API,以接收JSON响应。
var products
//Printify call for products list
(async () => {
try{
const list = await redd('shops/shopId/products.json');
//Catch the Data array and save it into the variable products
var obj = new JSONObject(response);
products = obj.getJSONArray("data");
}
catch(error) {
}
})();
//Print the variable products to the console
console.log(products)
我从响应中创建一个新的JSONObject并从该响应中获取数据数组,并将其放入此函数外部定义的Variable产品中。最后,我尝试将变量打印到控制台。
最终,我将需要使用“数据”数组并解析其中的特定项(即title: , description: , images:
),并将其作为值传递给下一个API。
目前,我从控制台收到“未定义”响应。不知道我在做什么错,希望我能得到一些帮助或指导。感激不尽,谢谢大家!
我终于能够使所有工作正常进行。自解决以来,实际上已经过了一分钟,但我想确保它能正常工作。这是最终为我工作的最终代码:
//Config for a new GOT instance, to use redd as the variable with the attached headers and options
const redd = got.extend({
prefixUrl: 'https://api.printify.com/v1',
responseType: 'json',
headers: {
'Authorization': 'Bearer ' + apiKey
}
});
var productsParsed //Setting up global variable to accept the array from the JSON response body
//Printify call for products list
getProducts = async () => {
try{
const response = await redd('shops/' + shopId + '/products.json');
productsParsed = response.body.data; //Data is the array in the body I need access to, and saving that into the var productsParsed
//Returning the var with the new value
return productsParsed
}
catch(error) {
console.log(error.response);
}
};
getProducts().then(console.log); //Printing the return value from getProducts() which verifies the var contains the needed value
因此,解决方案最终变得非常简单。我只是不完全了解GOT的结构。我必须使用点表示法来确定我的return语句。在弄清楚这一点之后,我便能够使用已设置为接受JSON响应正文值的全局变量。谢谢大家的建议和协助。我希望这篇文章能够在与我类似的情况下为其他人提供帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句