Failed call to Deezer API with React and axios

不想你离开。 提交于 2019-12-11 19:46:24

问题


I want to connect to Deezer API and read data, the API is available here, if you take first links they have there and open in a new tab you will see the data in json, however Axios can't return it

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:


Deezer api don't allow cross-origin request. So an api call from browser is not possible.

However you can use a workaround and use https://cors-anywhere.herokuapp.com

You need to change your code like following:

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

Here is a working example: https://stackblitz.com/edit/react-v6bufu

However, I will recommend to code your own backend where you will call Deezer's APIs. You won't be getting cross-origin error there.



来源:https://stackoverflow.com/questions/52985844/failed-call-to-deezer-api-with-react-and-axios

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!