Javascript is not accepting JSON data as variable - javascript

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

Related

How to remove unwanted characters from JSON request

I am new to javascript.
I am facing this issue where I get [{"_id":1}] as my results.
Does anyone know how can I get 1 as my output?
This is my code, I am calling it from a database.
function getaccountid() {
var accID = new XMLHttpRequest();
accID.open('GET', "http://127.0.0.1:8080/account" + "/" + sessionStorage.getItem("username"), true);
accID.setRequestHeader("Content-Type", "application/json");
accID.send(JSON.parse);
accID.onload = function () {
sessionStorage.setItem("accountId", accID.response)
}
}
That response type is a JSON formatted string, it's a standard response type, not an issue. To read the value you need to parse the result from a JSON string to an array of objects, then access it.
Also note that you need to remove the JSON.parse reference within the send() call and define the load event handler before you send the request. Try this:
function getaccountid() {
var accID = new XMLHttpRequest();
accID.addEventListener('load', function() {
let responseObject = JSON.parse(this.responseText);
sessionStorage.setItem("accountId", responseObject[0]['_id']);
console.log(responseObject[0]['_id']); // = 1
});
accID.open('GET', "http://127.0.0.1:8080/account/" + sessionStorage.getItem("username"), true);
accID.setRequestHeader("Content-Type", "application/json");
accID.send();
}

Why doesn't JSON.parse() work on this object?

const Http = new XMLHttpRequest();
const url='https://www.instagram.com/nasa/?__a=1';
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
console.log(Http.responseText);
var instaData = JSON.parse(Http.responseText);
console.log(instaData);
}
I'm trying to get a JSON object from an Instagram page so that I can extract some basic user data. The above code gets a string from Instagram that looks like a properly formatted JSON object, but when I try to use JSON.parse on it I get the error message "JSON.parse: unexpected end of data at line 1 column 1 of the JSON data".
I can't include the full output of Http.responseText because it's too long at 8,000+ characters, but it starts like this:
{"logging_page_id":"profilePage_528817151","show_suggested_profiles":true,"show_follow_dialog":false,"graphql":{"user":{"biography":"Explore the universe and discover our home planet. \ud83c\udf0d\ud83d\ude80\n\u2063\nUncover more info about our images:","blocked_by_viewer":false,"country_block":false,"external_url":"https://www.nasa.gov/instagram","external_url_linkshimmed":"https://l.instagram.com/?u=https%3A%2F%2Fwww.nasa.gov%2Finstagram&e=ATOO8om3o0ed_qw2Ih3Jp_aAPc11qkGuNDxhDV6EOYhKuEK5AGi9-L_yWuJiBASMANV4FrWW","edge_followed_by":{"count":53124504},"followed_by_viewer":false,"edge_follow":
You are trying to do a cross origin request without setting the Origin header. If a given api endpoint supports CORS, then when the Origin header is passed in the request it will reply with the "access-control-allow-origin" header.
I confirmed that the instagram url in your question does support CORS.
The following code using the fetch api works.
fetch('https://www.instagram.com/nasa/?__a=1', { mode: 'cors' })
.then((resp) => resp.json())
.then((ip) => {
console.log(ip);
});
You should read through the MDN CORS info https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS.
Here's also a fixed version of your original code:
const Http = new XMLHttpRequest();
const url = 'https://www.instagram.com/nasa/?__a=1';
Http.open("GET", url);
Http.setRequestHeader('Origin', 'http://local.geuis.com:2000');
Http.send();
Http.onreadystatechange = (e) => {
if (Http.readyState === XMLHttpRequest.DONE && Http.status === 200) {
console.log(Http.responseText);
}
}

Javascript FORTNITE API request

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

Getting 401 status while sending email using Gmail API in Chrome extension

I am getting the raw data of the drafted from Gmail API "get" method and sending it using Gmail API "send" method.
'var url = 'https://www.googleapis.com/gmail/v1/users/me/messages/id?
format=raw&alt=json&access_token=' + token;
url = url.replace("id", emailId);
var x = new XMLHttpRequest();
x.open('GET', url , true);
x.send();
x.onload = function() {
var jsonRes = JSON.parse(x.response);
sendEmail(jsonRes.raw);
}
function sendEmail(raw) {
if (raw) {
var request = new XMLHttpRequest();
var url = 'https://www.googleapis.com/gmail/v1/users/me/messages/send?alt=json&access_token=' + token;
params = "raw=" + raw;
request.open('POST', url , true);
request.setRequestHeader("Authorization", "Bearer " + token);
request.setRequestHeader("Content-type", "application/json");
request.send(params);
request.onload = function() {
if (200 === request.status) {
alert("Email sent successfully");
}
}
}`
I am getting 401 status.
If I am sending this raw data from API page itself, then it is sent successfully. Therefore the raw data is correct.
I am missing something while sending the email. Please help!
A 401 error means "invalid credentials", most likely because your token has expired or isn't valid.
The Google API explorer and Google Javascript libraries take care of the token for you (generally), but if you're calling the service endpoints directly with XMLHttpRequest(), you'll have to manage the token yourself.
If you want to go that route, here are the details you have to implement: https://developers.google.com/identity/protocols/OAuth2
You can try things out in the "Oauth2 playground": https://developers.google.com/oauthplayground/
Thank you for all responses.
I sent the email using the following code-
function sendEmail(raw) {
if (raw) {
var request = new XMLHttpRequest();
var url = 'https://www.googleapis.com/gmail/v1/users/me/messages/send';
var params = JSON.stringify({'raw': raw});
request.open('POST', url , true);
request.setRequestHeader("Authorization", "Bearer " + token);
request.setRequestHeader("Content-type", "application/json");
request.send(params);
request.onload = function() {
if (200 === request.status) {
alert("Email sent successfully");
}
}
}
}
There were two mistakes I rectified-
1. The token was sent in URL as well as header. It should be sent only in header.
2. The param raw was sent as String but it should be sent as a JSON object.

JSON.parse fails in function, works in console

I have a simple script that does a cross site request and gets data from a GitHub gist. The data from the Github API is returned as a JSON string. To allow further modification of the data, I want it as a JSON object.
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
var tmpJSON = "";
var gistData = "";
var gistID = "5789756";
var gitAPI = "https://api.github.com/gists/"
var gistQuery = gitAPI + gistID;
function incrementGist() {
gistData = createCORSRequest('GET', gistQuery);
gistData.send();
tmpJSON = JSON.parse(gistData.response);
}
In the html page, I have
<p><input type="button" value="Increment" OnClick="incrementGist()"></p>
If I actually hit the button, the error I get is:
Uncaught SyntaxError: Unexpected end of input
But if I subsequently open the console and run this:
var crap = JSON.parse(gistData.response);
it works just fine. This happens in both Firefox and Chrome. I really don't see why the JSON.parse command fails inside a function call, but not in the console. An actual page is set up here
The problem is that you're trying to read the response before the server answered.
You must read the response in a callback. For example :
gistData = createCORSRequest('GET', gistQuery);
gistData.onreadystatechange = function() {
if (gistData.readyState === 4) {
if (gistData.status === 200) {
tmpJSON = JSON.parse(gistData.response);
... use tmpJSON...
... which should not be called so as it is not JSON...
... maybe tmpObject ?
}
}
}
gistData.send();
That's because you are not waiting the request to actually finish. I don't know your API but try waiting the server response then parse your JSON. you could try with a SetTimeout first to see that it is working but you nee to do something like in jQuery with its' success:function(...) callback

Categories