如何解决如何通过函数使api获取请求?
我正在尝试使用Axios调用dog.ceo api,并通过链接到我的按钮的genNewImage()
函数发出的代码,在其下面使用品种名称生成一个新的随机狗图像,这是我的javascript :
function genNewImage(){
axios.get('https://dog.ceo/api/breeds/image/random') //This is the api I'm calling to.
.then((body) => {
var url = body.data.message;
var image = document.getElementById("dogImg");
var dogText = document.getElementById("dogText");
var urlCutter = url.split('/')[4].split('-'); //Get the breed name from the retrieved url
var first = urlCutter[1].charAt(0).toUpperCase() + urlCutter[1].split("").slice(1,urlCutter[1].length).join(""); //Get the first part of the breed name & capitalize first letter.
var second = urlCutter[0].charAt(0).toUpperCase() + urlCutter[0].split("").slice(1,urlCutter[0].length).join(""); //Get the second part of the breed name & capitalize first letter.
image.src = url; // set the src of the image object
dogText.innerHTML = "This is a: " + first + " " + second; //Set the dog breed name in the paragraph
})
.catch((err) => {
console.log('Error',err.statusCode);
})
};
<button onClick="genNewImage()">Click for a random image</button>
<img id="dogImg" src="">
<p><strong><span id ="dogText"> This is a: </span></strong></p>
一般来说,我还是Axios和api调用的真正新手。即使我已经使用此代码在新页面加载时进行api调用,我的函数也无法正常工作,我也不明白为什么这个代码不起作用。任何建议将不胜感激。
解决方法
问题不是代码本身,而是语义问题。
考虑这两个示例网址
https://images.dog.ceo/breeds/spaniel-cocker/n02102318_9714.jpg
https://images.dog.ceo/breeds/chow/n02112137_6458.jpg
逐行浏览代码,当您尝试获得品种的名字时,您会看到问题发生。您访问索引1处的拆分URL数组。用“-”分隔符拆分该数组。如果URL(品种)不像第二个URL一样包含“-”,则将引发错误,因为索引1处的数组未定义。因此,在使用索引1的值之前,请检查是否已设置。这将使您的代码运行。
该错误消息还表明未定义变量。
function genNewImage() {
axios.get('https://dog.ceo/api/breeds/image/random')
.then((body) => {
let url = body.data.message;
let image = document.getElementById("dogImg");
let dogText = document.getElementById("dogText");
let urlCutter = url.split('/')[4].split('-');
let first = typeof(urlCutter[1]) == 'undefined' ? "" : urlCutter[1].charAt(0).toUpperCase() + urlCutter[1].split("").slice(1,urlCutter[1].length).join("");;
let second = urlCutter[0].charAt(0).toUpperCase() + urlCutter[0].split("").slice(1,urlCutter[0].length).join("");
image.src = url; // set the src of the image object
dogText.innerHTML = "This is a: " + first + " " + second; //Set the dog breed name in the paragraph
})
.catch(error => {
console.log(error.response)
});
}
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<button onClick="genNewImage()">Click for a random image</button>
<img id="dogImg" src="">
<p><strong><span id ="dogText"> This is a: </span></strong></p>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。