Google Search Console API Sending Batch Requests in JS - javascript

i have a problem with performance of my code. I have to send a lot of requests to Google Search Console API. My code works fine but it takes too long.
I found information that i can send batch requests to API but i don't know how to do it in JavaScript.
https://developers.google.com/webmaster-tools/v1/how-tos/batch
I'm wondering if using batch requests will improve performence of my code and i looking for some information how i can implement batch requests to API in my code.
My code below
function loadData()
{
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.googleapis.com/webmasters/v3/sites/' + siteAdress + '/searchAnalytics/query?key=***');
xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);
xhr.send(JSON.stringify
({
"startDate": date1,
"endDate": date2,
"dimensions":[
"QUERY",
"PAGE"
],
"rowLimit": rowLimit,
"startRow": startRow
}));
xhr.onload = function()
{
response = JSON.parse(xhr.responseText);
for (let i = 0; i < response.rows.length; i++)
{
gscData.push([response.rows[i].keys[0], response.rows[i].keys[1], response.rows[i].impressions, response.rows[i].clicks, Math.round(response.rows[i].ctr*100)/100, Math.round(response.rows[i].position*100)/100]);
rowNumber++;
}
if(response.rows.length == rowLimit)
{
startRow += rowLimit;
loadData();
}
else
{
alert("Done");
}
};
}

Related

Querying the API via JavaScript / CORS (teamup.com calendar)

I am currently trying to figure out how to query the API of a calendar on teamup.com and retrieve data (events in the calendar) from it.
There's a code example on their website: Querying the API via JavaScript / CORS
I tried to make it work in Visual Studio, so I had to install XMLHttpRequest via npm and add a require code line:
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
// Creates a CORS request in a cross-browser manner
function createCORSRequest(method, url) {
var apiKey = 'API_KEY'; //placeholder for api key
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari/IE10+.
xhr.open(method, url, true);
xhr.setRequestHeader('Teamup-Token', apiKey);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE8/IE9.
xhr = new XDomainRequest();
// XDomainRequest does not support querying HTTPS from HTTP pages
if (window.location.protocol === 'http:') {
url = url.replace('https://', 'http://');
}
if (-1 === ['GET', 'POST'].indexOf(method)) {
alert('XDomainRequest only supports GET and POST methods');
return;
}
if (-1 === url.indexOf('?')) {
url += '?_teamup_token=' + apiKey;
} else {
url += '&_teamup_token=' + apiKey;
}
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
// Sends the actual CORS request.
function makeCorsRequest(url, successCallback, errorCallback) {
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function (xhr) {
if (xhr.target.status < 400) {
if (successCallback) successCallback(xhr.target);
} else if (errorCallback) {
errorCallback(xhr.target);
}
};
xhr.onerror = function (xhr) {
if (errorCallback) {
errorCallback(xhr.target);
}
};
xhr.send();
}
// Send a GET request for all events in a date range
makeCorsRequest(
'https://api.teamup.com/ks73ad7816e7a61b3a/events?startDate=2015-06-01&endDate=2015-06-05',
function(xhr) {
var data = JSON.parse(xhr.responseText);
alert('Successfully Received: ' + JSON.stringify(data));
},
function(xhr) {
var data = JSON.parse(xhr.responseText);
alert('Request failed with code '+ xhr.status +': ' + JSON.stringify(data));
}
);
When I try to run the program per node I get this terminal output:
PS C:\Users\...\Documents\GitHub\teamup-test> node team-up-test.js
C:\Users\...\Documents\GitHub\teamup-test\team-up-test.js:45
if (xhr.target.status < 400) {
^
TypeError: Cannot read properties of undefined (reading 'target')
at exports.XMLHttpRequest.xhr.onload (C:\Users\...\Documents\GitHub\teamup-test\team-up-test.js:45:17)
at exports.XMLHttpRequest.dispatchEvent (C:\Users\...\Documents\GitHub\teamup-test\node_modules\xmlhttprequest\lib\XMLHttpRequest.js:591:25)
at setState (C:\Users\...\Documents\GitHub\teamup-test\node_modules\xmlhttprequest\lib\XMLHttpRequest.js:614:14)
at IncomingMessage.<anonymous> (C:\Users\...\Documents\GitHub\teamup-test\node_modules\xmlhttprequest\lib\XMLHttpRequest.js:447:13)
at IncomingMessage.emit (node:events:539:35)
at endReadableNT (node:internal/streams/readable:1345:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
So it seems like the program cannot read xhr.target.status, but why?
Summarized: I want to fetch calendar event data from my calendar on team-up per JS and display that data on a discord bot.
I am wondering if I even do need CORS since it's only for browsers. Hoping someone could guide me into the right direction please.
The code tutorial here: https://apidocs.teamup.com/#querying-the-api-via-javascript--cors is to be executed in the browser, in the client. I don't think it can be used in the server. Remember, Node.js is a back-end language, it runs on the server, not on the browser.
You can make an API call in Node.js with the code below, but you should study Axios later
const https = require('https');
const options = {
hostname: 'api.teamup.com',
path: '/ks73ad7816e7a61b3a/events?startDate=2015-06-01&endDate=2015-06-05',
headers: {
"Teamup-Token" : "API_KEY"
},
};
https.get(options, (resp) => {
let data = '';
resp.on('data', (receivedDataBuffer) => {
data += receivedDataBuffer;
});
resp.on('end', () => {
let receivedDataAsJSON = JSON.parse(data);
//do what you need with the json
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});

How can I get Text from Js to Python

<script>
function voice(){
var recognition = new webkitSpeechRecognition();
recognition.lang = "en-GB";
recognition.onresult = function(event){
console.log(event);
document.getElementById("speechto").value = event.results[0][0].transcript;
}
recognition.start();
}
</script>
I am making language translator web-app. And in above code, it takes input from the user using mic and print that in textarea in eng language. So I want this text in my python so that I can translate it and print it on another textarea. But i dont know how can I get that text from the js into my python code.
any soln?
Where is "your python"? I'm assuming this is on a browser over a network. You gotta set up a webserver (in python) to listen to network responses. Try webpy for a simple solution: https://webpy.org/.
You'll have to set up a URL endpoint to respond to POST requests. More info here: https://webpy.org/docs/0.3/tutorial#getpost.
And lastly, you'll have to set up your Javascript to send the post request and to use the response from your server to edit the textarea. You can use the JS fetch API to send the post request and handle the response from there.
Good luck hooking everything up
I assume you're using flask as that is tagged in your question. You need to establish a route to execute your python code and run your flask app which should listen to some TCP port on your computer (by default flask seems to use port 5000).
Then on your js code you can use the fetch method to send the text to that port. For example:
fetch('http://locahost:5000/{your flask route goes here}', {
method: 'POST',
headers: {
'Content-Type': 'text/plain',
},
body: {text you want to send goes here},
})
rather than using python just to do a translation, why not to use a simple javascript translate function?
var translate = async (t,src,dst) => {
var tt = new Promise(function(resolve) {
var i=0, len=0, r='', tt='';
const url = 'https://clients5.google.com/translate_a/';
var params = 'single?dj=1&dt=t&dt=sp&dt=ld&dt=bd&client=dict-chrome-ex&sl='+src+'&tl='+dst+'&q='+t;
var xmlHttp = new XMLHttpRequest();
var response;
xmlHttp.onreadystatechange = function(event) {
if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
response = JSON.parse(xmlHttp.responseText);
for (var i = 0, len = response.sentences?.length; i < len; i++) {
var r=(((response.sentences[i].trans).replace('}/g','')).replace(')/g','')).replace('\%20/g', ' ');
r=((r.replace('}','')).replace(')','')).replace('\%20/g', ' ');
tt += r;
}
if (tt.includes('}'||')'||'%20')) {
tt=((tt.replace('}/g','')).replace(')/g','')).replace('\%20/g', ' ');
}
resolve(tt);
}
}
xmlHttp.open('GET', url+params, true);
xmlHttp.send(null);
xmlHttp.onreadystatechange();
});
return await tt;
}

Calling Azure DevOps REST API using JavaScript

I am currently trying to make a GET call to Azure DevOps Rest API using JavaScript however, I am having a hard time doing so. How will I be able to accomplish this?
This is what I have for the uri.
uri: https://dev.azure.com/<team project>/_apis/projects?api-version=2019-12-01
Please take a look here. You have there an example.
But if you want to use pure vanila here you have sth:
var request = new XMLHttpRequest()
request.open('GET', 'https://dev.azure.com/thecodemanual/_apis/projects?api-version=5.1', true)
request.setRequestHeader('Content-Type', 'application/json; charset=utf-8;');
request.setRequestHeader ("Authorization", "Basic " + btoa('Basic' + ":" + 'YOUR_PAT_TOKEN'));
request.onload = function() {
// Begin accessing JSON data here
var data = JSON.parse(this.response)
if (request.status >= 200 && request.status < 400) {
console.log(data)
} else {
console.log('error')
}
}
request.send()

Azure Mobile Service and Javascript

Hi there i am stuck and somehow don't find the solution. It seems simple but, well ok. Here it goes. I have a mobile service in Azure and i want to reach that one with javascript. How do i get around the 401 Unauthorized? I tried with the documentation supplied from MS but no luck. This is what i got so far (adding the key to the url is not working of course) what can i add to get it to work?
var client = new WindowsAzure.MobileServiceClient(
"https://cdshop.azure-mobile.net/",
"vGpqzyApJXXXXXXXXblQCWne73"
);
var getJSON = function (url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function () {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
$(function () {
$('#clickme').click(function () {
getJSON('http://cdshop.azure-mobile.net/api/cds/total?key=vGpqzyApJXXXXXXXXblQCWne73', function (err, data) {
if (err != null) {
alert('Something went wrong: ' + err);
} else {
alert('Your Json result is: ' + data.result);
result.innerText = data.result;
}
});
});
});
If you are creating your own HTTP requests, you need to set a request header called X-ZUMO-APPLICATION with your Application Key, e.g. "vGpqzyApJXXXXXXXXblQCWne73", for tables and APIs that are set to "application" or "users". (Assuming you are still using Mobile Services; the newer App Service does not use this X-ZUMO-APPLICATION header.) Tables and APIs set for "users" also need an X-ZUMO-AUTH request header with the user's authentication token.
Alternatively, you can use the MobileServiceClient you created in the first line, and it will do this for you. This page has examples for calling APIs and tables. For your example:
client.invokeApi("cds", {
body: null,
method: "get"
}).done(function (data) {
alert('Your Json result is: ' + data.result);
result.innerText = data.result;
}, function(error) {
alert('Something went wrong: ' + error);
});

How to set multiple HTTP headers in JavaScript get () method

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();

Categories