使用React和axios未能成功调用Deezer API [英] Failed call to Deezer API with React and axios

查看:112
本文介绍了使用React和axios未能成功调用Deezer API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想连接到Deezer API并读取数据,该API在此处可用,如果您选择其中的第一个链接,然后在新标签页中打开,您将看到json中的数据,但是Axios无法退回它

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);

推荐答案

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

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

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

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);
  });

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

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

但是,我建议您对自己的后端进行编码,以供调用 Deezer的API.您不会在那儿遇到跨域错误.

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.

这篇关于使用React和axios未能成功调用Deezer API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆