簡體   English   中英

使用 axios 反應從超級英雄 api 獲取數據

[英]Fetch data from superhero api using axios react

我需要在 React 應用程序中使用 Axios 從https://superheroapi.com/獲取數據。 我在控制台中沒有任何警告消息,但仍未獲取數據。 頁面加載器正在加載但沒有響應。

這是我的代碼。

應用程序.jsx

import React, { useState } from 'react';
import './App.css';
import {
  InputGroup,
  Input,
  InputGroupAddon,
  Button,
  FormGroup,
  Label,
  Spinner
} from 'reactstrap';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.min.css';
import axios from 'axios';
import BookCard from './BookCard.jsx';
function App() {
  // States
  const [maxResults, setMaxResults] = useState(10);
  const [startIndex, setStartIndex] = useState(1);
  const [query, setQuery] = useState('');
  const [loading, setLoading] = useState(false);
  const [cards, setCards] = useState([]);
  // Handle Search
  const handleSubmit = () => {
    setLoading(**false**);
    if (maxResults > 40 || maxResults < 1) {
      toast.error('max results must be between 1 and 40');
    } else {
      axios
        .get(
           
          `https://www.superheroapi.com/api.php/my-api-key/search/${query}&maxResults=${maxResults}&startIndex=${startIndex}`

        )
        .then(res => {
          if (startIndex >= res.data.totalItems || startIndex < 1) {
            toast.error(
              `max reults must be between 1 and ${res.data.totalItems}`
            );
          } else {
            if (res.data.items.length > 0) {
              setCards(res.data.items);
              setLoading(false);
            }
          }
        })
        .catch(err => {
          setLoading(true);
          console.log(err.response);
        });
    }
  };
  // Main Show Case
  const mainHeader = () => {
    return (
      <div className='main-image d-flex justify-content-center align-items-center flex-column'>
        {/* Overlay */}
        <div className='filter'></div>
        <h1
          className='display-2 text-center text-white mb-3'
          style={{ zIndex: 2 }}
        >
          Search
        <div style={{ width: '60%', zIndex: 2 }}>
          <InputGroup size='lg' className='mb-3'>
            <Input
              placeholder='Book Search'
              value={query}
              onChange={e => setQuery(e.target.value)}
            />
            <InputGroupAddon addonType='append'>
              <Button color='secondary' onClick={handleSubmit}>
                <i className='fas fa-search'></i>
              </Button>
            </InputGroupAddon>
          </InputGroup>
          <div className='d-flex text-white justify-content-center'>
            <FormGroup >
              <Label for='maxResults'>Max Results</Label>
              <Input
                type='number'
                id='maxResults'
                placeholder='Max Results'
                value={maxResults}
                onChange={e => setMaxResults(e.target.value)}
              />
            </FormGroup>
            <FormGroup className='ml-5'>
              <Label for='startIndex'>Start Index</Label>
              <Input
                type='number'
                id='startIndex'
                placeholder='Start Index'
                value={startIndex}
                onChange={e => setStartIndex(e.target.value)}
              />
            </FormGroup>
          </div>
        </div>
      </div>
    );
  };

  const handleCards = () => {
    if (loading) {
      return (
        <div className='d-flex justify-content-center mt-3'>
          <Spinner style={{ width: '3rem', height: '3rem' }} />
        </div>
      );
    } else {
      const items = cards.map((item, i) => {
        let thumbnail = '';
        if (item.volumeInfo.imageLinks) {
          thumbnail = item.volumeInfo.imageLinks.thumbnail;
        }

        return (
          <div className='col-lg-4 mb-3' key={item.id}>
            <BookCard
              thumbnail={thumbnail}
              title={item.volumeInfo.name}
        
            />
          </div>
        );
      });
      return (
        <div className='container my-5'>
          <div className='row'>{items}</div>
        </div>
      );
    }
  };
  return (
    <div className='w-100 h-100'>
      {mainHeader()}
      {handleCards()}
      <ToastContainer />
    </div>
  );
}

export default App;

這是我在瀏覽器中運行 url( https://www.superheroapi.com/api.php/my-api-key/search/batman ) 時的 json output

{
    "response": "success",
    "results-for": "batman",
    "results": [{
        "id": "69",
        "name": "Batman",
        "powerstats": {
            "intelligence": "81",
            "strength": "40",
            "speed": "29",
            "durability": "55",
            "power": "63",
            "combat": "90"
        },
        "biography": {
            "full-name": "Terry McGinnis",
            "alter-egos": "No alter egos found.",
            "aliases": ["Batman II", "The Tomorrow Knight", "The second Dark Knight", "The Dark Knight of Tomorrow", "Batman Beyond"],
            "place-of-birth": "Gotham City, 25th Century",
            "first-appearance": "Batman Beyond #1",
            "publisher": "DC Comics",
            "alignment": "good"
        },
        "appearance": {
            "gender": "Male",
            "race": "Human",
            "height": ["5'10", "178 cm"],
            "weight": ["170 lb", "77 kg"],
            "eye-color": "Blue",
            "hair-color": "Black"
        },
        "work": {
            "occupation": "-",
            "base": "21st Century Gotham City"
        },
        "connections": {
            "group-affiliation": "Batman Family, Justice League Unlimited",
            "relatives": "Bruce Wayne (biological father), Warren McGinnis (father, deceased), Mary McGinnis (mother), Matt McGinnis (brother)"
        },
        "image": {
            "url": "https:\/\/www.superherodb.com\/pictures2\/portraits\/10\/100\/10441.jpg"
        }
    }, {
        "id": "70",
        "name": "Batman",
        "powerstats": {
            "intelligence": "100",
            "strength": "26",
            "speed": "27",
            "durability": "50",
            "power": "47",
            "combat": "100"
        },
        "biography": {
            "full-name": "Bruce Wayne",
            "alter-egos": "No alter egos found.",
            "aliases": ["Insider", "Matches Malone"],
            "place-of-birth": "Crest Hill, Bristol Township; Gotham County",
            "first-appearance": "Detective Comics #27",
            "publisher": "DC Comics",
            "alignment": "good"
        },
        "appearance": {
            "gender": "Male",
            "race": "Human",
            "height": ["6'2", "188 cm"],
            "weight": ["210 lb", "95 kg"],
            "eye-color": "blue",
            "hair-color": "black"
        },
        "work": {
            "occupation": "Businessman",
            "base": "Batcave, Stately Wayne Manor, Gotham City; Hall of Justice, Justice League Watchtower"
        },
        "connections": {
            "group-affiliation": "Batman Family, Batman Incorporated, Justice League, Outsiders, Wayne Enterprises, Club of Heroes, formerly White Lantern Corps, Sinestro Corps",
            "relatives": "Damian Wayne (son), Dick Grayson (adopted son), Tim Drake (adopted son), Jason Todd (adopted son), Cassandra Cain (adopted ward)\nMartha Wayne (mother, deceased), Thomas Wayne (father, deceased), Alfred Pennyworth (former guardian), Roderick Kane (grandfather, deceased), Elizabeth Kane (grandmother, deceased), Nathan Kane (uncle, deceased), Simon Hurt (ancestor), Wayne Family"
        },
        "image": {
            "url": "https:\/\/www.superherodb.com\/pictures2\/portraits\/10\/100\/639.jpg"
        }
    }, {
        "id": "71",
        "name": "Batman II",
        "powerstats": {
            "intelligence": "88",
            "strength": "11",
            "speed": "33",
            "durability": "28",
            "power": "36",
            "combat": "100"
        },
        "biography": {
            "full-name": "Dick Grayson",
            "alter-egos": "Nightwing, Robin",
            "aliases": ["Dick Grayson"],
            "place-of-birth": "-",
            "first-appearance": "-",
            "publisher": "Nightwing",
            "alignment": "good"
        },
        "appearance": {
            "gender": "Male",
            "race": "Human",
            "height": ["5'10", "178 cm"],
            "weight": ["175 lb", "79 kg"],
            "eye-color": "Blue",
            "hair-color": "Black"
        },
        "work": {
            "occupation": "-",
            "base": "Gotham City; formerly Bludhaven, New York City"
        },
        "connections": {
            "group-affiliation": "Justice League Of America, Batman Family",
            "relatives": "John Grayson (father, deceased), Mary Grayson (mother, deceased), Bruce Wayne \/ Batman (adoptive father), Damian Wayne \/ Robin (foster brother), Jason Todd \/ Red Hood (adoptive brother), Tim Drake \/ Red Robin (adoptive brother), Cassandra Cain \/ Batgirl IV (adoptive sister)"
        },
        "image": {
            "url": "https:\/\/www.superherodb.com\/pictures2\/portraits\/10\/100\/1496.jpg"
        }
    }]
}

這是 my.network 選項卡的輸出

在此處輸入圖像描述

首先,為什么要使用setLoading(true); 下面的代碼塊應該是false 正如您所說,加載程序永遠不會結束,那么我認為您可能會進入 catch 塊。

.catch(err => {
          setLoading(true);
          console.log(err.response);
        });

現在,如果要捕獲塊,請使用 static api 檢查您的代碼,因為目前代碼中沒有任何錯誤。

axios
        .get(`https://www.superheroapi.com/api.php/my-api-key/search/batman`)
        .then(res => {
          console.log("response= ", res);
        })
        .catch(err => {
          setLoading(true);
          console.log(err.response);
        });

如果它正常工作,則意味着您的查詢有問題。

我沒有經過身份驗證,所以我無法運行這些查詢,但如果我不得不猜測,我會說你沒有正確附加你的查詢參數。

axios.get(`https://www.superheroapi.com/api.php/my-api-key/search/${query}&maxResults=${maxResults}&startIndex=${startIndex}`)

您似乎正在發送"batman&maxResults=10&startIndex=1"作為您要搜索的名稱。

格式正確的查詢參數字符串以? 特點。 所以請求應該看起來更像https://www.superheroapi.com/api.php/my-api-key/search/${query}?maxResults=${maxResults}&startIndex=${startIndex}形成一個帶有諸如"batman?maxResults=10&startIndex=1"等參數的名稱請求。

axios GET 請求代碼將是

axios.get(`https://www.superheroapi.com/api.php/my-api-key/search/${query}?maxResults=${maxResults}&startIndex=${startIndex}`)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM