How do you use API keys in HTTP Requests? - javascript

I am struggling to work out if there is a way to use an API key when trying to call data from an endpoint and if so, where would I put it?
var request = new XMLHttpRequest("Ocp-Apim-Subscription-Key: {KEY}")
// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://api.sportsdata.io/v3/mlb/scores/json/AreAnyGamesInProgress')
request.onload = function () {
// Begin accessing JSON data here
}
// Send request
request.send()

You need to put it in a HTTP request header most of the times.
var request = new XMLHttpRequest();
request.open('GET', 'https://api.sportsdata.io/v3/mlb/scores/json/AreAnyGamesInProgress');
request.setRequestHeader("Ocp-Apim-Subscription-Key", "{KEY}");
request.onload = function () {
//...
};
request.send();
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader

Related

Getting "Unexpected end of JSON input at JSON.parse

Just getting a Syntax Error, "Unexpected end of JSON input at JSON.parse"
var trivia;
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var request = new XMLHttpRequest();
request.open('GET', 'https://opentdb.com/api.php?amount=5&category=15&difficulty=easy&type=boolean');
request.send();
trivia = JSON.parse(request.responseText);
console.log(trivia);
The problem is that you need to wait for the response to arrive before continuing on. You can achieve just that using the AJAX request's onload event:
var trivia;
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var request = new XMLHttpRequest();
request.open('GET', 'https://opentdb.com/api.php?amount=5&category=15&difficulty=easy&type=boolean');
request.onload = function() {
trivia = JSON.parse(request.responseText);
console.log(trivia);
}
request.send();

XMLHTTPRequest POST getting stuck

I am trying to POST to a google maps service. If you click on the URL you will see the JSON response that I am expecting to get
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest()
var url = "https://maps.googleapis.com/maps/api/directions/json?origin=Exeter&destination=Deal&region=uk&mode=driving"
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
// do something to response
alert(this.responseText)
}
However, this code gets stops after xhr.onload = function(). So I never get the response back. Is there an error in my code?
You forgot to send the request.
xhr.send("The string of application/x-www-form-urlencoded data you are POSTING goes here");
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest()
var url = "https://maps.googleapis.com/maps/api/directions/json?origin=Exeter&destination=Deal&region=uk&mode=driving"
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
// do something to response
alert(this.responseText)
}
xhr.send("data to be send");
Try this.

XMLHttpRequest response: preflight request does not pass the access control check:

I am trying to subscribe to a firebase cloud messaging topic with the following http post request:
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://iid.googleapis.com/iid/v1/etLaB36oW1w...nyO_Zc26ZPOFTeNuf58-l6uSoJ9Xs1JRYKfqxsmKkdrR-oX4tQsuS_z5C0/rel/topics/Byfjordskole");
xhr.setRequestHeader("authorization", "key=AAAABlxTfxY:APA91bGE3sa09zq...dZSIVJul3N-y1hMJqAoKngwjC_El3rEuH4_-S2gOxKcdAF67HHhGK7pAWJrhyt8JthJGm_QN6JdXTBow62nYodgFvLncfSniwtBinBgIPLaKpT");
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "a3ce72a5-f8ba-99e4-59d6-fe3295b84f6e");
xhr.send(data);
This works when I use Postman, but I get the following error message when I try to use the same code on my javascript app:
XMLHttpRequest cannot load https://iid.googleapis.com/iid/v1/eOEiRqvhD4s:APA91bFFb-uP-Xhf2iD-ALUI_X4M7…gA_YgQgmuib7cCL7UuSdlhUUWmsqwRnkcO2kpAIV_H-_xBPlPd/rel/topics/Eiganesskole.
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'https://sk......e.top' is therefore not allowed access.
Do firebase cloud messaging inhibit me from making this types of request, or is there a solution to this problem? Any help will be highly appreciated.
This Stack Overflow answer solved my problem: https://stackoverflow.com/a/2067584/6177181
The problem was browser security related: and this kept me from making cross domain requests. The Solution was to wrap my code in script tags to avoid this restriction. So instead of doing this request from another javascript file, I simply added the request code in the index.html file like this:
<script>
function subscribe(currentToken){
"use strict"
let stored_topics = localStorage.getItem("topicsList");
let topics = JSON.parse(stored_topics);
for (let i = 0; i < topics.length; i++){
let data = null;
let xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
let body = {};
let url = "https://iid.googleapis.com/iid/v1/"+currentToken+"/rel/topics/"+topics[i];
xhr.open("POST", url);
xhr.setRequestHeader("authorization", "key=AAAABlxTfxY:....QAVfBJI8J0RdZSIVJul3N-y1hMJqAoKngwjC_El3rEuH4_-S2gOxKcdAF67HHhGK....2nYodgFvLncfSniwtBinBgIPLaKpT");
xhr.setRequestHeader("content-type", "application/json");
xhr.send(data);
}
}
</script>
(The currentToken is requested from the firebase cloud messaging API in the same file(index.html)).
Follow the instructions on this link :https://firebase.google.com/docs/cloud-messaging/js/receive for information about Firebase cloud messaging.

XmlHttpRequest get callback response when request fails

I have a simple request I make to my service:
var request = new XMLHttpRequest();
request.open("OPTIONS", url, true);
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
request.setRequestHeader('Accept', 'application/json');
request.onreadystatechange = function () {
if (request.readyState != 4) {
return;
}
var authType = request.getResponseHeader("WWW-Authenticate");
makeRequest(...);
};
request.send();
}
So what I'm trying to achieve is make a call to my endpoint to see what's the authorisation type (basic or bearer) and then when I get the auth type I will make the actual request with the proper credentials.
If I make the request manually I get the 401 unauthorised which is normal but I also get the WWW-Authenticate: Basic ... in my headers. However if I do this javascript call it will just fail with 401:unauthorised but I don't get this failed response in my callback so the authType will be undefined.
I haven't used javascript before so the question is how can I get the response in the callback even if the request failed with unAuthorised ?
XMLHttpRequest has an onerror callback that you can use:
var request = new XMLHttpRequest();
...
request.onerror = function(){
if (this.status == 401) {
}
}
...
request.send();

Can I get via javascript the HTTP expires header of a HTTP resource?

My page needs to know when the cache a included javascript file will expire, to retrieve it again.
The XMLHTTPRequest object has a getResponseHeader method you can call:
// The following script:
var client = new XMLHttpRequest();
client.open("GET", "test.txt", true);
client.send();
client.onreadystatechange = function() {
if (this.readyState == 2) {
alert(client.getResponseHeader("Expires"));
}
}

Categories