【问题标题】:Multiple Fetch API Call returns error 403 (the second API call is not ran)多个 Fe​​tch API 调用返回错误 403(第二个 API 调用未运行)
【发布时间】:2020-12-13 13:58:55
【问题描述】:

我正在尝试为我正在处理的英雄联盟 API 项目执行多个 API 获取调用。之所以必须做多次API调用,是为了先获取用户的accountId。当我通过第一个 API 调用获取帐户 ID 时,我需要使用 accountId 进行第二个 API 调用以获取玩家的比赛历史统计数据,这可以通过第二个 API 调用来完成。总体而言,我正在尝试获取玩家的比赛历史记录,以便将其放入图表中以显示用户的“最常使用的冠军”但是,无法运行第二个 API 调用,并且代码返回错误 403。

错误

import React, {Component} from 'react'
import ChartData from './ChartData'

class Chart extends Component {
constructor(props) {
    super(props)
    this.state = {
        error: null,
        isLoaded: false,
        stats: [],
        matchHistory: null,
        chartData: {},
        accountId: ''
    }
}

componentDidMount() {
    this.getUserInfo();
}

getUserInfo = () => {
    const proxyurl = "https://mysterious-wave-96239.herokuapp.com/";
    const url = "https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/" + this.props.username + "?api_key=" +process.env.REACT_APP_SECRET_KEY;
    fetch(proxyurl + url)
    .then(res => res.json())
    .then(
        (result) => {
            this.setState({
                isLoaded: true,
                stats: result,
                accountId: result.accountId
            }
            ,console.log(`this is the users account id = ` + result.accountId));
        },
        (error) => {
            this.setState({
                isLoaded: true,
          error: {
              message: "Error - Something went wrong!"
            }
        });
    }
    )
}




render () {
    return (
        <div className="chart">
        <ChartData accountId={this.state.accountId} />
        </div>
    )
   }
}
export default Chart
    import {Bar
    // ,Line
    // ,Pie
    } from 'react-chartjs-2'

    class ChartData extends Component {
    constructor(props) {
        super(props)
        this.state = {
            error: null,
            isLoaded: false,
            stats: [],
            matchHistory: null,
            chartData: {}
        }
    }

    componentDidMount() {
        this.getMatchHistory();
        this.getChartData();
    }

     getMatchHistory () {
        const proxyurl = "https://mysterious-wave-96239.herokuapp.com/";
        const url = "https://na1.api.riotgames.com/lol/match/v4/matchlists/by-account/" + this.props.accountId + "?endIndex=20&api_key=" +process.env.REACT_APP_SECRET_KEY;
        fetch(proxyurl + url)
        .then(res => res.json())
        .then(
            (result) => {
                this.setState({
                    isLoaded: true,
                    matchHistory: result
                }
                ,console.log(result)
                );
            },
            (error) => {
                this.setState({
                    isLoaded: true,
              error: {
                  message: "Error - Something went wrong!"
                }
            });
        }
        )
    }


    getChartData(){
        this.setState({
          chartData:{
            labels: ['Zed', 'Akali', 'Nunu', 'Luxe', 'Amumu', 'Fiona', 'Yassuo'],
            datasets:[
              {
                label:'Population',
                data:[
                    8,
                    2,
                    4,
                    4,
                    1,
                    1,
                    3
                ],
                backgroundColor:[
                  'rgba(255, 99, 132, 0.6)',
                  'rgba(54, 162, 235, 0.6)',
                  'rgba(255, 206, 86, 0.6)',
                  'rgba(75, 192, 192, 0.6)',
                  'rgba(153, 102, 255, 0.6)',
                  'rgba(255, 159, 64, 0.6)',
                  'rgba(255, 99, 132, 0.6)'
                ]
              }
            ]
          }
        });
      }

    static defaultProps = {
        displayTitle: true,
        displayLegends: true,
        legendPosition: 'right'
    }
    
    render () {
        return (
            <div className="chart">
                <Bar
                    data={this.state.chartData}
                    options={{
                        scales: {
                            yAxes: [{
                              ticks: {
                                beginAtZero: true
                              }
                            }]
                          },
                        title: {
                        display: this.props.displayTitle,
                        text: "Most played champions in 20 games",
                        fontSize: 25
                    },
                    legend: {
                    display: this.props.displayLegend,
                    position: this.props.legendPosition
                    }
                }}
                />
            </div>
        )
         }
      }
           export default ChartData```

【问题讨论】:

  • 您正在验证您的请求吗?
  • @DanielA.White 您能否详细说明验证我的请求是什么意思?
  • 你为什么将proxyUrlurl 连接起来?你被“禁止”了,那可能是你的 api 参数没有正确编码?
  • @Icepickle 我必须连接一个代理 URL,否则我会收到此 CORS 错误 - 访问从源 'localhost:3000' 获取的 'na1.api.riotgames.com/lol/match/v4/matchlists/by-account/…' 已被 CORS 策略阻止:否请求的资源上存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

标签: javascript html css reactjs api


【解决方案1】:

通过使用生命周期方法 componentDidMount() 而不是组件来解决这个问题,同时输入 if else 语句来捕获重新渲染的错误

import ChartData from './ChartData'

class Chart extends Component {
    constructor(props) {
        super(props)
        this.state = {
            error: null,
            isLoaded: false,
            stats: [],
            matchHistory: null,
            chartData: {},
            accountId: ''
        }
    }

    

    componentDidMount = () => {
        const proxyurl = "https://mysterious-wave-96239.herokuapp.com/";
        const url = "https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/" + this.props.username + "?api_key=" +process.env.REACT_APP_SECRET_KEY;
        fetch(proxyurl + url)
        .then(res => res.json())
        .then(
            (result) => {
                this.setState({
                    isLoaded: true,
                    stats: result,
                    accountId: result.accountId
                }
                ,console.log(`this is the users account id = ` + result.accountId));
            },
            (error) => {
                this.setState({
                    isLoaded: true,
              error: {
                  message: "Error - Something went wrong!"
                }
            });
        }
        )
    }

    

    
    render () {
    const { error, isLoaded } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else if(isLoaded) {
        return (
            <div className="chart">
            <ChartData accountId={this.state.accountId} />
            </div>
        )
        }
    }
}
export default Chart```

【讨论】:

    猜你喜欢
    • 2020-04-15
    • 1970-01-01
    • 2013-06-14
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    相关资源
    最近更新 更多