使用React和axios对Deezer API的调用失败

时间:2018-10-25 09:25:12

标签: reactjs axios

我想连接到Deezer API并读取数据the API is available here,如果您将first links放在那里,并在新标签页中打开,您将在json中看到数据,但是Axios无法退还

import React from "react";
import ReactDOM from "react-dom";

import axios from "axios";

import "./styles.css";

class App extends React.Component {

  componentDidMount() {
    axios.get("https://api.deezer.com/album/302127")
    .then(response => {
      console.log(response);
    })
    .catch(err => {
      console.log(err);
    });
  }

  render() {
    return (
      <div className="App">
        <h2>Deezer</h2>
      </div>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

1 个答案:

答案 0 :(得分:2)

Deezer api不允许跨域请求。因此无法通过浏览器进行api调用。

不过,您可以使用变通办法并使用https://cors-anywhere.herokuapp.com

您需要像下面这样更改代码:

axios.get("https://cors-anywhere.herokuapp.com/https://api.deezer.com/album/302127")
  .then(response => {
    this.setState({ response })
  })
  .catch(err => {
    console.log('error', err);
  });

这是一个有效的示例:https://stackblitz.com/edit/react-v6bufu

  

但是,我建议您对自己的后端进行编码,以供调用   Deezer的API。您将不会在这里收到跨域错误。