today i started learning js with api and i want to ask how to fix this.
I registred on fortnite tracker and created api.
api is like:
GET https://api.fortnitetracker.com/v1/profile/{platform}/{epic-nickname}
and api key is like:
TRN-Api-Key: xxxxxxx-xxxxxxxxxxx-xxxxxxxxxx
I found something here that i need to do it:
var xhttp = new XMLHttpRequest();
xhttp.request("GET", "api", true);
xhttp.setRequestHeader('TRN-Api-Key' "KEY");
xhttp.send();
but when i do it like this, it will show me error CORS and i don't know how ti fix that.
Thanks <3
i think you need to set these headers to allow cors origin
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();
I didn't found solution for this api so i looked for other apis.
i found Fortnite api by https://fortniteapi.com/
name api is:
https://fortnite-public-api.theapinetwork.com/prod09/users/id?username=YOUR_NAME
example name api:
https://fortnite-public-api.theapinetwork.com/prod09/users/id?username=Ninja
there you get UID. You copy that UID and place it to this api with platfrom (pc,ps4)
https://fortnite-public-api.theapinetwork.com/prod09/users/public/br_stats?user_id=UID&platform=pc
example stats api:
https://fortnite-public-api.theapinetwork.com/prod09/users/public/br_stats?user_id=4735ce9132924caf8a5b17789b40f79c&platform=pc
JS CODE:
/* 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>
hope that will help someone
Related
I am trying to connect to an API to display some data on my website.
I've already defined Http as new XMLHttpRequest();, and url as the API endpoint.
Here's the code:
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
var api = JSON.stringify(Http.responseText)
document.getElementById("stat").innerHTML = "Powering over " + api.total_bandwidth.TB + "TB of private internet traffic"
}
However, when I run the code, I get the following error:
Uncaught TypeError: api.total_bandwidth is undefined
What is wrong here? Is Http.responseText already an Object? Did I define the API wrong?
This is the response of api:
{"total_bandwidth": {"GB": 110842.05, "TB": 108.24, "PB": 0.11}}
You're stringifying the object (response), then trying to get "TB" from a string.
Try parsing api then getting the properties from it:
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
var api = JSON.stringify(Http.responseText);
var apiJson = JSON.parse(api);
document.getElementById("stat").innerHTML = "Powering over " + apiJson.total_bandwidth.TB + "TB of private internet traffic";
};
Edit: Turns out that "JSON.stringify" was actually a mistake.
I think you meant to use JSON.parse rather than JSON.stringify... - Robin Zigmond
I think you meant JSON.parse (to PARSE the response text) instead of JSON.stringify:
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
var api = JSON.parse(Http.responseText);
document.getElementById("stat").innerHTML = "Powering over " + api.total_bandwidth.TB + "TB of private internet traffic"
}
Learn more about JSON.parse at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
I'm trying to make a PSOT request to the Microsoft Oauth2.0 token URL using NodeJS and the XMLHttpRequest library found here. However, I am having the problem, that I just can't send a proper Request body alongside with the Request. I have already tried using FormData from here, I tried URLSearchParams, and I tried making it a String in the way we know it from our Adress bar in GET Requests. Below you can see my Code from when I tried doing it in a GET URL form, and in the part that I made a commend, you can see my attempts of using FormData instead.
var xhr = new XMLHttpRequest();
xhr.open("POST", 'https://login.microsoftonline.com/common/oauth2/v2.0/token');
/*var data = new FormData();
//var data = new URLSearchParams();
data.append('client_id', clientId);
data.append("grant_type", "authorization_code");
data.append("scope", "openid email profile");
data.append("code", code);
data.append("redirect_uri", "http://" + req.headers.host + req.url);
data.append("client_secret", secret);
Error message on this one: TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received an instance of FormData
Same message with URLSearchParams, except it received an instance of URLSearchParams
*/
var data = 'client_id=' + clientId;
data += '&grant_type=authorization_code';
data += '&scope=openid%20email%20profile';
data += '&code=' + code;
data += '&redirect_uri=' + encodeURIComponent("http://" + req.headers.host + req.url);
data += '&client_secret=' + secret;
//This one gives me an error message from Microsoft: {"error":"invalid_request","error_description":"AADSTS900144: The request body must contain the following parameter: 'grant_type'.\r\nTrace ID: ratherNotSay\r\nCorrelation ID: ratherNotSay\r\nTimestamp: 2020-02-10 10:37:36Z","error_codes":[900144],"timestamp":"2020-02-10 10:37:36Z","trace_id":"ratherNotSay","correlation_id":"ratherNotSay","error_uri":"https://login.microsoftonline.com/error?code=900144"}
//This must mean that the request body can not have been submitted in the right way.
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
console.log(xhr.status + "\n" + xhr.responseText + "\n");
}
};
xhr.send(data);
You can transform a URLSearchParams instance into a query string, like the one that you build manually, by using the toString() method.
I don't know if the Content-Type header is set to application/x-www-form-urlencoded by default in the node-XMLHTTPRequest version, but it couldn't hurt to set it manually.
const xhr = new XMLHttpRequest();
xhr.open("POST", 'https://login.microsoftonline.com/common/oauth2/v2.0/token');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
const data = new URLSearchParams();
data.append('client_id', clientId);
data.append("grant_type", "authorization_code");
data.append("scope", "openid email profile");
data.append("code", code);
data.append("redirect_uri", "http://" + req.headers.host + req.url);
data.append("client_secret", secret);
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
console.log(xhr.status + "\n" + xhr.responseText + "\n");
}
};
xhr.send(data.toString());
I am trying to get the locations list of a user with Google My Business Javascript API (https://developers.google.com/my-business/quickstarts/javascript). A user logs in successfully with his google credentials and oauth token is generated. But When I am trying to get the locations--->
var apiKey = 'xxxxxxxxxxxxxx';
var clientId = 'xxxxxxxxxxxxxxxxxxxxxxxx';
var gmb_api_version = 'https://mybusiness.googleapis.com/v4';
let user = gapi.auth2.getAuthInstance().currentUser.get();
let oauthToken = user.getAuthResponse().access_token;
let xhr = new XMLHttpRequest();
let req = gmb_api_version + '/' + 'accounts/' + user.getId() + '/locations';
xhr.responseType = 'json';
xhr.open('GET', req);
xhr.setRequestHeader('Authorization', 'Bearer ' + oauthToken);
xhr.send();
I am getting null in xhr.response object.
It is somehow late to answer but in case somebody needs:
If you do not have the error then probably, just the account has no locations. first check the google response in [https://developers.google.com/oauthplayground/], trying to see if you have the different response.
I have been searching the total Internet from around a week and finally decided to post here. I want to send an HTTP get request to an API with two headers for authentication. These are custom headers and need to be sent at once.
I have tried the following code but it never gives me success. The API returns a JSON file which will have parameters like "title", "description". The URL and headers work fine, when I tried it using hurl.it.
This is the code. Please suggest some answer to solve this problem. And one more thing is, I want to do it using JavaScript only, no jQuery, AJAX, or AngularJS.
var xmlhttp = new XMLHttpRequest();
var url = "https://affiliate- api.flipkart.net/affiliate/offers/v1/dotd/json";
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 &&xmlhttp.status==200) {
var myArr = JSON.parse(xmlhttp.responseText);
function display(arr) {
var i;
var out = " ";
for(i = 0; i < arr.length;i++) {
out += "<p>title:" + arr.dotd[i].title + "<br>description:" + arr.dotd[i].description + "<br></p>";
}
document.getElementById("p1").innerHTML = out;
}
}
else {
alert(xmlhttp.status);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader("Fk-Affiliate- Token","xxxxxxxxxxxxxxxxx");
xmlhttp.setRequestHeader("Fk-Affiliate-Id","xxxxxxxxx");
xmlhttp.send();
How can I authenticate the Microsoft translate API and gt it working on my localhost ?
I have attempted to use my microsoft primary key and client_id to no avail. I really have no clue. Help!!
**note: ** the client.setRequestHeader() method below.
Thanks in advance.
function _translate(text, to, from){
var promise = new Promise(function(resolve, reject){
var API = "https://api.datamarket.azure.com/Bing/MicrosoftTranslator/v1/translate?" +
"Text=" + encodeURIComponent(text) +
"&To=" + encodeURIComponent(to) +
"&From=" + encodeURIComponent(from);
var client = new XMLHttpRequest();
client.open('POST', API, true);
client.setRequestHeader('Authorization', 'Basic ' + 'what-goes-here-exactly??');
client.onload = function(){
if (client.status >= 200 && client.status > 300){
resolve(client.responseText);
}else{
reject(client.response);
}
};
client.error = function(){
reject(client.response);
};
client.send();
});
return promise;
}
_translate("I love pizza", 'en', 'es')
.then(function(translation){
alert(translation);
});
According to this msdn page you would set the header as follows:
client.setRequestHeader('Authorization', 'Bearer ' + your_access_key);
You obtain your access token by following these instructions, in short:
Subscribe to the Microsoft Translator API on Azure Marketplace
Register your application Azure DataMarket
Make an HTTP POST request to the token service