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.
Related
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}`;
I'm facing an issue and I cannot find a way to overcome it. If I send a ZPL command to print a label via XMLHttpRequest() like this:
var request = new XMLHttpRequest();
var method = "POST";
var async = true;
var zpl = "^XA...^XZ";
var urlForPrint = "http://192.168.0.242/printer/pstprnt";
var urlForHi = "http://192.168.0.242:9100";
request.onload = function () {
var status = request.status; // HTTP response status, e.g., 200 for "200 OK"
var data = request.responseText; // Returned data, e.g., an HTML document.
}
request.open(method, urlForPrint, async);
request.overrideMimeType('text/plain; charset=unicode');
request.send(zpl);
it all works fine (prints the label). But before trying to print anything, I need to send the command ~HI, which, according to the documentation, should return a string with a number of properties, related to the printer at this IP.
The problem: I cannot receive this string.
var requestForPrinter = new XMLHttpRequest();
requestForPrinter.onerror = function (e) {
//...
}
requestForPrinter.onload = function (e) {
// I suppose that response message should arrive here, as a parameter of e
//...
}
requestForPrinter.open(method, urlForHi, async);
requestForPrinter.send("~HI");
If I use PuTTY, the printer returns the message and it is displayed in the PuTTY console.
After a lot of research, I realized that PuTTY communicates with the printer via TCP/IP, while I'm trying to communicate with it via HTTP. So I have now got a clear idea what is the problem. But how to solve it?
A colleague of mine suggested creating a socket. So I tried WebSocket, TCPSocket, socket.IO with no success. Also, they seem not to be supported by all popular browsers and I couldn't manage to test them because of errors, which appeared in the browser's console. Tried to fix them with no luck.
Any help will be appreciated! Thank you!
edit: I found this. So my second question is: I am just starting to learn node.js and find out its capabilites. I read somewhere, that It is a server-side js library. Can I use it only client-side? I mean, they have to be able to print labels using the printer in their LAN and to be able to work even if the Internet connection drops (to ask the server for data only once, at the beginning, when it loads some data into a JqGrid). So communicating with a server is not an option here.
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(...);
I'm a very beginner in JavaScript, I recently learned it at school indeed. I have to include and get responses from the OpenWeatherMap API on a web page. For now, all I want to do is getting the temperature in the city specified in the API's URL.
I struggled a long time before asking for your assistance but I couldn't figure my problem out.
Here is my code :
var btn = document.getElementById("btn");
var p = document.getElementById("paragraphe");
var txtf = document.getElementById("txtf");
btn.addEventListener('click', fun, false);
function fun(){
var xhr = new XMLHttpRequest();
xhr.open('GET','http://api.openweathermap.org/data/2.5/weatherq=London&appid=2de143494c0b295cca9337e1e96b00e0&units=metric', true)
xhr.addEventListener('readystatechanged', function(){
if(xhr.readyState == 4 && xhr.status == 200){
var obj = JSON.parse(xhr.responseText)
p.innerHTML = obj.main.temp;
}
}, false)
xhr.send();
}
Thank you for your help !
At first glance, check your spelling. I can't see your HTML, but possible issues could be: #paragraphe and #txtf.
Also, change the event name readystatechanged to readystatechange.
One tip, add console.log("insert check data here"); throughout your code. That way to can see in the console log where it is breaking. This really helps with trouble shooting!
I'm trying to get the direction_in_traffic, which isn't returned using the regular directions api. I've found that there is a field in the distancematrix api that does just that.
This code works when I run it from my own machine, but once it is online, I see errors concerning Access-Control-Allow-Origin
var durationInTraffic = function(from, to, mode, callback) {
var key = 'API-KEY';
var address = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=' + from + '&destinations=' + to + '&key='+ key +'&travelmode=' + mode + '&departure_time=now';
var req = new XMLHttpRequest();
req.addEventListener('load', function(){
if (typeof callback === 'function') {
callback(JSON.parse(this.responseText).rows[0].elements[0].duration_in_traffic.value);
}
});
req.open('GET',address);
req.setRequestHeader('Access-Control-Allow-Origin','https://haroen.me');
req.setRequestHeader('Access-Control-Allow-Headers','X-Requested-With');
req.send();
};
I've created the key, but at the domain verification tab it seems to "forget" what addres I've put in.
jsbin (which obviously won't work since this key isn't allowed on that domain, but I get the same error on my own domain).
The full code I'm trying this on is visible at https://github.com/haroenv/maps-checker
Thanks for your help!
So as #dandavis suggested in a comment, the reason why this didn't work is because Google wants this response to be server-side. My workaround is as follows: a php (or any server-side solution) that mirrors the request to Google. An example implementation is this:
<?php
echo file_get_contents('https://maps.googleapis.com/maps/api/distancematrix/json?origins=' . urlencode($_POST['from']) . '&destinations=' . urlencode($_POST['to']) . '&key='. urlencode(json_decode(file_get_contents('config.json'), true)['maps-key']) .'&mode=' . urlencode($_POST['mode']) . '&departure_time=now');
?>
And then I send a request to that script from within my main client-side script.