Failed call to Deezer API with React and axios

2019-09-04 16:14发布

问题:

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.



标签: reactjs axios