无法从此API检索数据

时间:2019-07-05 08:59:48

标签: javascript reactjs cors

我已经在react中开发了这个实时搜索组件,该组件根据输入的搜索值从API检索数据。但是,当指向此API https://api.itbook.store/1.0/search/program

时,它不会检索或显示数据。

但是当我使用类似http://hn.algolia.com/api/v1/search?query=redux这样的API时,它将检索数据

  const [data, setData] = useState({ books: [] });
  const [query, setQuery] = useState('program');
  const [url, setUrl] = useState(
    'https://api.itbook.store/1.0/search/program',
  );

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(url);

      setData(result.data);
    };

    fetchData();
  }, [url]);

  return(
    <Paper className={classes.root}>

      <Container maxWidth="lg">

        <form className={classes.container} encType="multipart/form-data">

          <TextField
            required
            id="standard-required"
            placeholder="Enter Book Name"
            label="Search for a Book"
            name="bookName"
            value={query}
            onChange={event => setQuery(event.target.value)}
            className={classes.textField}
            multiline
            rowsMax="2"
          margin="normal"/>

          <Button onClick={() =>
            setUrl(`https://api.itbook.store/1.0/search/${query}`)
          }
            className={classes.button} color="primary">Search</Button>

          <ul>
            {data.books.map(item => (
              <li key={item.objectID}>
                <a href={item.url}>{item.title}</a>
              </li>
            ))}
          </ul>


        </form>

      </Container>

    </Paper>

我希望我的代码从API Json收集数据:https://api.itbook.store/1.0/search/something

1 个答案:

答案 0 :(得分:1)

@sideshowbarker为该问题提供了一个极好的解决方案Trying to use fetch and pass in mode: no-cors

要解决 CORS 问题,基本上可以做的是通过 CORS代理URL发出请求。

这是一个有效的沙箱,其中包含代码更新: https://codesandbox.io/s/lucid-kapitsa-w1uid

import React, { useState } from "react";
import ReactDOM from "react-dom";
import axios from "axios";

import "./styles.css";

const App = () => {
  const [url, setUrl] = useState("https://api.itbook.store/1.0/search/");
  const [query, setQuery] = useState("");
  const [results, setResults] = useState([]);

  const fetchData = async () => {
    const proxyURL = "https://cors-anywhere.herokuapp.com/";
    const updatedURL = `${proxyURL}${url}${query}`;
    const res = await axios(updatedURL);

    setResults(res.data.books);
  };

  const createBookList = () => {
    return results.map(book => {
      return (
        <div>
          <h4>{book.title}</h4>
        </div>
      );
    });
  };

  return (
    <div>
      <input onChange={e => setQuery(e.target.value)} value={query} />
      <button onClick={fetchData}>Click</button>
      <div>{createBookList()}</div>
    </div>
  );
};