Arcgis: authentification via JS application - javascript

I am writing a program using JavaScript, which connects to a local ArcGIS server through ArcGIS REST API and loads the maps.
The URL to get service is
let xmlhttp = new XMLHttpRequest();
xmlhttp.withCredentials = true;
let url = "http://domain/arcgis/rest/services/" + serviceName +"/MapServer/" + layer_id + "/query?f=json&where=1%3D1&returnGeometry=false&outFields=*";
I can get the token through the API. The problem is, I can't set it in cookies, as the browser rejects programmatically writing another domain.
May someone suggest a workaround?

You can add &token=abcd1234 to your url, so you get :
let token = 'abcd1234';
let url = `http://domain/arcgis/rest/services/${serviceName}/MapServer/${layer_id}/query?f=json&where=1%3D1&returnGeometry=false&outFields=*&token=${token}`;

Related

Forbidden request status while using oxford dictionary API in javascript

I am learning to use web apis. I started with oxford dictionary api and read this documentation. This is the code I have written so far.
const app_id = '8***c965';
const app_key = '395******162b317b9d6f3c6cd0b3930b';
const language = "en";
var word_id = 'oblivion';
var url = 'https://od-api.oxforddictionaries.com:443/api/v1/entries/' + language + '/' + word_id.toLowerCase();
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.setRequestHeader('app_id', app_id);
request.setRequestHeader('app_key', app_key);
request.setRequestHeader('Accept', "application/json");
request.onload = function() {
//Begin accessing JSON data here
var data = JSON.parse(this.response);
console.log(data);
}
request.send();
This code returns status 403 Forbidden in the console. According to the documentation, this should have worked. Can anybody shed some light about what I am doing wrong? Any help is greatly appreciated!
You have exceeded a monthly limit. The limit is 3k per month.
You can see it in "statistic" tab on https://developer.oxforddictionaries.com.
For development it is better to use some mock server in order to save hits for real application.
If none of what mentioned above fixed the issue this could be it.
Their API version 1 got shut down on 30 June 2019 and replaced by V2.
From their documentation:
Users on a FREE account will need to update their plan to either
Prototype or Developer to get access to v2. More information about our
new plans is available here.
Use 'v1' in the URL to request version 1, and 'v2' to request version
2.
Read about migration guide here: https://developer.oxforddictionaries.com/version2

How can I get the parent site, or the site where the file was sent from, in javascript?

I'm writing a node.js application with client-side javascript that uses fetch to get data from the node API that I wrote. I want to be able to put that application on any site (URL) without changing anything in the javascript. My current code goes something like fetch("http://localhost:8080/data.json"). If I wanted to deploy onto Heroku, for example, I would have to change that. Is there a way to overcome this fact?
Window location might do the trick, if I am understanding correctly. Set it into a variable like this:
For browser:
If the hostname is http://localhost:8000, using this:
// http://localhost:8000/data.json
var url = window.location.hostname + "/data.json";
fetch(url)
Heres another example.
document.getElementById("demo").innerHTML =
"Page location is " + window.location.href;
Result is
Page location is https://www.w3schools.com/js/js_window_location.asp
More info:
https://www.w3schools.com/js/js_window_location.asp
I see you wanted NodeJS, for server
var os = require("os");
var port = process.env.PORT || 8000
var url = os.hostname;
var final = url + ":" + port
// localhost:port
var hostname = os.hostname();

Making getAsync request in Javascript for Windows Phone

I am trying to make a request to a backend API I created on Google App Engine. Right now it should be pretty simple, it sends the URL, and what should be returned is JSON that looks like this {"keys": [5676073085829120]}. I have tested the API by making CURL requests, and the the URL works, one thing that confuses me is that when I make a CURL request I have to specify "Accept: application/json", but I do not know how to add that to a getAsync request. Here is the code in question:
function verify(){
var uname = document.getElementById("username").value;
var pword = document.getElementById("password").value;
var c = new Windows.Web.Http.HttpClient();
var complete = "http://golden-bonsai-124817.appspot.com/users/" + uname + "/" + pword;
c.getAsync(new Windows.Foundation.Uri(complete)).done(function (result) {
var jsonResult = JSON.parse(result.content.toString());
var key = jsonResult.Results.series[0].data;
console.log("in here");
var authKey = new Array();
key.forEach(function (cur, i, arr) {
authKey.push(cur.keys);
});
};
I tried stepping through the code with the debugger in visual studio. It initializes the variables, and the value of my 'complete' variable is the correct URL that I have used for my cURL requests. I set a breakpoint inside of the function that is supposed to happen once the request completes, but the code never makes it inside of that function and eventually the windows phone emulator goes black and it seems like it just hangs, it doesn't exit but it gets to a point where I can no longer step through. I have been trying and trying but I just can't figure it out, and to make it worse the documentation for all of this stuff is garbage. Any help would be very greatly appreciated. Thanks in advance.
That need to be specified in the content of a request. To specify the content type of a request, you need to use HttpRequestMessage to create request and then specify the media type. You then need to use sendRequestAsync method of HttpClient to process your request. So your code will be something similar to the following.
var hc = new Windows.Web.Http.HttpClient();
var uri = new Windows.Foundation.Uri("http://golden-bonsai-124817.appspot.com/users/" + uname + "/" + pword);
var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.get, uri);
var content = "";
var encoding = Windows.Storage.Streams.UnicodeEncoding.utf8;
var mediaType = "application/json";
request.content = new Windows.Web.Http.HttpStringContent(content, encoding, mediaType);
hc.sendRequestAsync(request).then(...);

Serving a different JS file from a server depending on the number of times a URL is visited by a client?

I've an web app that injects a server based myjavascriptfile.js file from my server, using jQuery AJAX GET request. Currently, this GET request is called every time the client visits https://www.google.co.uk.
However I'd like to be able to send mysecondjavascriptfile.js file to the client, if the client has gone to https://www.google.co.uk more that 10 times.
Do you have any ways I can do this?
First thing to do, is to persist the hits the client do to the site. I think SessionStorage could help here:
sessionStorage.counter = ++(sessionStorage.counter) || 0;
var sources = {
lessThanTen : 'http://yourscript.com/lessthan10hits.js',
moreThanTen : 'http://yourscript.com/morethan10hits.js'
}
var script = document.createElement('script');
if(sessionStorage.counter >= 10){
script.src = sources.moreThanTen;
} else {
script.src = sources.lessThanTen;
}
document.getElementsByTagName('head')[0].appendChild(script);
This is of course a client-side verification of the hit. You could implement a server-side verification through AJAX or just serve a slightly different HTML markup after 10 requests. You'll need to use sessions (or just plain cookies) to persist them on the server-side.
AJAX verification:
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', function(){
var script = document.createElement('script');
script.src = xhr.response;
document.getElementsByTagName('head')[0].appendChild(script);
});
xhr.open('POST', 'http://www.urltocheckhits.com/hits');
xhr.send('url=' + encodeURIComponent(window.location.hostname));
And then from Node.js (with body-parser and express-session):
var sources = {
lessThanTen : 'http://yourscript.com/lessthan10hits.js',
moreThanTen : 'http://yourscript.com/morethan10hits.js'
}
app.post('/hits', urlEncoded, function(req, res){
if(req.body){
var url = req.body.url;
if(!req.session.views){
req.session.views = { };
}
if(req.session.views[url]){
req.session.views[url]++;
} else {
req.session.views[url] = 1;
}
if(req.session.views[url] > 10){
res.send(sources.moreThanTen);
} else {
res.send(sources.lessThanTen);
}
}
});
I suggest you check the documentation of express-session and body-parser.
Note that you'll need to add CORS Headers for this (you could just as easily do it with JSONP too instead of using XHR).
Might be easier if you just serve the JS file instead of doing the AJAX call and then including the returned script. So then you could just:
<script src="http://onesingleurl.com/hits">
Caching will behave weird like this though, so that's why I favor the other approach.

Calling API from CouchDB Design Doc

I am wondering if it is possible to make an API call from within a design doc. I have tried the code below, however I am getting the following error message.
{"error":"forbidden","reason":"CSRF Cookie/Header mismatch"}
This is the code:
function(head, req) {
var id = req.query.id;
var contactName = 'This is the new contact name!!';
var sendString = '{"PrimaryContactName":"' + contactName + '"}';
var xhr = new XMLHttpRequest();
xhr.open('PUT", <URL>, false);
xhr.send(sendString);
var sendStatus = xhr.status;
}
Thanks!
You aren't going to be able to use AJAX from CouchDB. (it's not a web browser)
If you want changes in your database to be propagated to other data-sources, you can use the _changes feed. That will be a much more robust solution no matter how you slice it.

Categories