Javascript FORTNITE API请求

时间:2019-01-27 13:02:30

标签: javascript html api

今天我开始用api学习js,我想问一下如何解决这个问题。

我在Fortnite Tracker上注册并创建了api。

api就像:

GET https://api.fortnitetracker.com/v1/profile/{platform}/{epic-nickname}

和api键就像:

TRN-Api-Key: xxxxxxx-xxxxxxxxxxx-xxxxxxxxxx

我在这里找到了需要做的事情:

var xhttp = new XMLHttpRequest();
xhttp.request("GET", "api", true);
xhttp.setRequestHeader('TRN-Api-Key' "KEY");
xhttp.send();

但是当我这样做时,它将向我显示错误CORS,我不知道该如何解决。

感谢<3

2 个答案:

答案 0 :(得分:1)

我认为您需要设置这些标头以允许cors起源

var xhttp = new XMLHttpRequest();
xhttp.request("GET", "api", true);
xhttp.setRequestHeader('Access-Control-Allow-Origin', '*');
xhttp.setRequestHeader('Access-Control-Allow-Headers', '*');
xhttp.setRequestHeader('Access-Control-Allow-Methods', '*');
xhttp.setRequestHeader('TRN-Api-Key' "KEY");
xhttp.send();

答案 1 :(得分:0)

我没有找到该api的解决方案,所以我在寻找其他api。

我通过https://fortniteapi.com/找到了Fortnite api

名称api是:

https://fortnite-public-api.theapinetwork.com/prod09/users/id?username=YOUR_NAME

示例名称api:

https://fortnite-public-api.theapinetwork.com/prod09/users/id?username=Ninja

您有UID。您复制该UID并使用platfrom(pc,ps4)将其放置到此api中

https://fortnite-public-api.theapinetwork.com/prod09/users/public/br_stats?user_id=UID&platform=pc

示例统计信息API:

https://fortnite-public-api.theapinetwork.com/prod09/users/public/br_stats?user_id=4735ce9132924caf8a5b17789b40f79c&platform=pc

JS代码:

/*  your uid and platform  */
let uid = "4735ce9132924caf8a5b17789b40f79c";
let platform = "pc";

/*  fortnite api link provided by <fortniteapi.com>  */
let statApi = "https://fortnite-public-api.theapinetwork.com/prod09/users/public/br_stats?user_id=" + uid + "&platform=" + platform;

httpRequestAsync(statApi, theResponse);

/*  getting response from API and defining variables   */
function theResponse(response){
  console.log("getting stats of "  + uid);
  let jsonObject = JSON.parse(response);
  //example of getting data from api
  console.log("Name: " + jsonObject.username);
  console.log("Wins: " + jsonObject.totals.wins);
  console.log("Kills: " + jsonObject.totals.kills);
  console.log("K/D: " + jsonObject.totals.kd);
  console.log("Matches: " + jsonObject.totals.matchesplayed);
  console.log("Winrate: " + jsonObject.totals.winrate + "%");
};

/*  sending XMLHHttpRequest api  */
function httpRequestAsync(api, callback){
  var httpRequest = new XMLHttpRequest();
  httpRequest.onreadystatechange = () => {
    if (httpRequest.readyState == 4 && httpRequest.status == 200)
    callback(httpRequest.responseText);
  }
  httpRequest.open("GET", api, true);
  httpRequest.send();
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

希望对某人有帮助