简体   繁体   中英

How do I select certain data from API using AJAX and Axios?

I want to know what I am doing wrong when selecting a URL (or any data piece) from an API using Axios. Just as an example, I would like to select the URL: "https://media4.giphy.com/media/yy6hXyy2DsM5W/giphy-downsized.gif?cid=482277c2s3j1s8uell6vhu03111i46npv57g8yqgikgiefr8&rid=giphy-downsized.gif"

from the API link: https://api.giphy.com/v1/gifs/search?q=$puppies&api_key=MhAodEJIJxQMxW9XqxKjyXfNYdLoOIym

My HTML and Javascript is included. My function is grabbing all the API data, but it seems my res.data[0].images.downsized.url isn't written accurately. Any help would be much appreciated!

 async function getGiphs() { const res = await axios.get(`https://api.giphy.com/v1/gifs/search?q=$puppies&api_key=MhAodEJIJxQMxW9XqxKjyXfNYdLoOIym`); console.log(res.data[0].images.downsized.url); }
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Giphy Party!</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> </head> <body> <div class="jumbotron"> <h1 class="display-4 mb-3">GIPHY Party!</h1> <div class="form-group"> <form> <input id="search-word" class="form-control mb-3" placeholder="Enter search term"> <button id="search-btn" class="btn btn-primary btn-md mr-2" role="button" type="submit">Search GIPHY <button id="remove-btn" class="btn btn-danger btn-md" role="button">Remove Images </form> </div> <script src="giphyParty.css"></script> <script src="https://code.jquery.com/jquery-3.2.1.js"></script> <script src="https://unpkg.com/axios/dist/axios.js"></script> <script src="giphyParty.js"></script> </body> </html>

 /* i dont know see where and how you'r calling 'getGiphs' method. there is a small correction in accessing the results. */ async function getGiphs() { const res = await axios.get(`https://api.giphy.com/v1/gifs/search?q=$puppies&api_key=MhAodEJIJxQMxW9XqxKjyXfNYdLoOIym`); console.log(res.data.data[0].images.downsized.url); }

您只需要再添加一个“数据”,因为返回的对象也有一个名为“数据”的属性。

console.log(res.data.data[0].images.downsized.url)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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