Reactjs错误:未捕获(承诺)错误:请求失败,状态码为401

时间:2020-08-11 10:53:29

标签: javascript reactjs http-status-code-401 twitch twitch-api

实际上,我正在按照本教程https://www.youtube.com/watch?v=VTY6ZzDTV3A&t=197s

react.js 中的 Twitch电视仪表板上工作。

一切正常,但我的twitch api均不工作,请有人可以帮助我解决该错误。

这是我的控制台中显示的错误:

Uncaught (in promise) Error: Request failed with status code 401
    createError createError.js:16
    settle settle.js:17
    handleLoad xhr.js:61
createError.js:16
    fetchData Games.js:30
    AsyncFunctionThrow self-hosted:697

这是我正在处理的代码,如下所示:

Games.js:

import React, { useState, useEffect } from "react";
import api from "../api";
import { Link } from "react-router-dom";


function Games() {

    const [games, setGames] = useState([]);

    useEffect(() => {

        const fetchData = async () => {
    const result = await api.get("https://api.twitch.tv/helix/games/top");
      
         // console.log(result.data);

         let dataArray = result.data.data;
         let finalArray = dataArray.map(game => {
            let newURL = game.box_art_url
          .replace("{width}", "300")
          .replace("{height}", "300");

          game.box_art_url = newURL;
 


         })

         setGames(result.data.data);

    };

    fetchData();

    });

    return (
        <div>

    <h1>Most Popular Games</h1>
       
       <div className="row">

    {games.map(game => (
        <div className='col-4'>

        <div className='card'>
          <img className="card-img-top" src={game.box_art_url} />
              <div className="card-body">
                <h5 className="card-title">{game.name}</h5>
                <button className="btn btn-success">
                  <Link
                    className="link"
                    to={{
                      pathname: "game/" + game.name,
                      state: {
                        gameID: game.id
                      }
                    }}
                  >
                    {game.name} streams{" "}
                  </Link>
                </button>
              </div>


        </div>  

        </div>

        ))}

        </div>

    </div>

);

}

export default Games;

此外,这是我的api.js文件,我在其中添加了twitch电视api ID:

import axios from 'axios';


let api = axios.create({
    headers: {
         "Client-ID": '4mfy053h9jf3zqwy3fh1pi55oadib1'
    }

});

export default api;

2 个答案:

答案 0 :(得分:0)

重新启动您的 React 服务器开发,以便将标头发送到远程服务器

答案 1 :(得分:0)

您应该阅读 twitch 文档,以防您想要 GET https://api.twitch.tv/helix/games 需要添加更多标题。您需要授权:Bearer 和 Client-id。您可以查看here