Error: create_flow on surveyMonkey API (Javascript) - javascript

I'm having a problem using surveyMonkey API.
I'm able to use any public method except the Crate_flow and Send_flow.
these two raise me an error in the console:
OPTIONS
http://api.surveymonkey.net/v2/client/create_flow?api_key=**MYAPI* 596 (596) Index.html:61 XMLHttpRequest cannot load http://api.surveymonkey.net/v2/client/create_flow?api_key=**MYAPI*. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. Index.html:61 Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://api.surveymonkey.net/v2/client/create_flow?api_key=**MYAPI*'.
the code that I'm using is this:
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://api.surveymonkey.net/v2/batch/send_flow?api_key="+MYAPI, false);
xhr.setRequestHeader('Access-Control-Allow-Origin' ,'*');
xhr.setRequestHeader('Authorization','bearer '+TOKEN);
xhr.setRequestHeader('Content-Type', 'application/json');
var body = '{"survey_id" :"54681373","collector":{"type":"email", "recipients":[{"email": "martins.nuno.santos#gmail.com", "first_name": "Nuno", "last_name": "Santos"}],"send":true}, "email_message":{"reply_email":"martins.nuno.santos#gmail.com", "subject":"YOLO", "body_text": "Vamos lá experimentar isto ! [SurveyLink], para remover carrega em [RemoveLink]"}}';
xhr.send(body);
console.log(xhr.status);
console.log(xhr.statusText);
console.log(xhr.responseText);

SSL Required
The reason you're getting that error message is that you're accessing the API using the wrong protocol (HTTP instead of HTTPS). Since SSL is required, you're getting an error message in the body of the response <h1>Service Requires SSL</h1>. That message, however, does not come to you with the "Access-Control-Allow-Origin" header and is triggering this error message.
If you change http://api.surveymonkey.net to https://api.surveymonkey.net, you should be good to go.
As a side note: the "Access-Control-Allow-Origin: *" header is something the server will send back to you. It's not something you need to send to the server. It's what's missing in the response you're getting. You can safely remove the line adding it to you request from your code.

Related

I get a CORS-Error while doing a request for a API using XHR

We’re making a request for an API from one of our online-distributors.
However, we get a CORS-Error.
Access to XMLHttpRequest at 'https://api.cloud.im/marketplace/eu/products' from origin 'http://www.im-cmp.ch' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
We did the request in Postman and it worked. I tried to set the requestHeaders the exact same way they are set in Postman (including the hidden headers), however, there is an Error since the hidden headers can’t be set.
Refused to set unsafe header "Host"
Is this a client or a server problem? Am I maybe missing a requestHeader?
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://api.cloud.im/marketplace/eu/products");
xhr.setRequestHeader("X-Subscription-Key", "OUR PERSONAL SUBSCRIPTION KEY");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "OUR BEARER TOKEN");
// xhr.setRequestHeader("Host", "http://www.im-cmp.ch/");
xhr.setRequestHeader("accept", "*/*");
// xhr.setRequestHeader("Accept-Encoding", "gzip, deflate, br");
// xhr.setRequestHeader("Connection", "keep-alive");
xhr.send();
This is definitely a server problem.
The server has to send the Access-Control-Allow-Origin-header: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS.
Also, the error states that this happened during a preflight-request, meaning there was a OPTIONS request made beforehand, which would also need the response-header(s) needed for CORS.
The request works in Postman, since CORS is a feature only really relevant in browsers, to protect users.
Edit:
Also it is important that the server allows the request-headers you are sending using the Access-Control-Allow-Headers-header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers

Getting the Bad request error 400 trying to send XMLHttpRequest to http://api.lbs.yandex.net/geolocation

I need to send XMLHttpRequest to the Yandex server
I get the Bad Request error (400) and:
XMLHttpRequest cannot load http://api.lbs.yandex.net/geolocation. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost' is therefore not allowed access.
The response had HTTP status code 400.
Here is my code:
var xhr = new XMLHttpRequest();
var url = "http://api.lbs.yandex.net/geolocation";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
<some code>
};
var data = JSON.stringify({
"common": {
"version": "1.0",
"api_key": <here goes API key>
},
"gsm_cells": [
{
"countrycode": params[0],
"operatorid": params[1],
"cellid": params[3],
"lac": params[2],
"age": 0
}
]
});
xhr.send(data);
I can't find the solution for such a simple(?) thing!
That API expects application/x-www-form-urlencoded-formatted data that looks like this:
json={"common":{"version":"1.0","api_key":…}…}
That is, it needs a key=value pair, with the string json as the key and some JSON as the value.
But the code in the question is sending some JSON without the necessary json= preceding it. So the API endpoint responds with a 400 to tell you it’s a bad request.
So you can fix that and get a response back by making your code instead do this:
var data = 'json=' + JSON.stringify({…});
However, even after you do that, your browser’s still not going to let your frontend JavaScript access the response the server returns. Instead the browser will log an error message like this:
Failed to load https://api.lbs.yandex.net/geolocation: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin https://foo.bar is therefore not allowed access.
…because the CORS protocol requires browsers to disallow frontend JavaScript code access to responses from cross-origin requests unless the response has Access-Control-Allow-Origin.
But you can get around that by making the request through a CORS proxy; complete example:
var xhr = new XMLHttpRequest();
var proxyurl = "https://cors-anywhere.herokuapp.com/";
var url = "https://api.lbs.yandex.net/geolocation";
xhr.open("POST", proxyurl + url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
console.log(xhr.responseText)
};
var data = 'json=' + JSON.stringify({
"common": {
"version": "1.0",
"api_key": "AAwkGkwBAAAA9muWLAMAKp9XjTBZtmOLeiBQJqHX6YEqNdUAAAAAAAAAAAAoEP1ZsBlcVFA_OpP55MK3Ek1r8A=="
},
"gsm_cells": [{
"countrycode": 250,
"operatorid": 99,
"cellid": 42332,
"lac": 36002,
"age": 0
}]
});
xhr.send(data);
Note however that if you send the request through a third-party proxy like that, the operator of the proxy can potentially snoop on your api_key and any other credentials you might send.
So you’re better off setting up your own proxy using https://github.com/Rob--W/cors-anywhere/
As far as how the proxy in example above works: Prefixing https://cors-anywhere.herokuapp.com/ to your request URL causes the request to get made through that proxy, which then:
Forwards the request to whatever https://api.lbs.yandex.net/geolocation.
Receives the response from https://api.lbs.yandex.net/geolocation.
Adds the Access-Control-Allow-Origin header to the response.
Passes that response, with that added header, back to your requesting frontend code.
The browser will then allow your frontend code to access the response, because that response with the Access-Control-Allow-Origin response header is what the browser sees.
See also https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Suggested sulution will not work correctly in common case, but works correctly for gcm cell. It's because yandex.net/geolocation service used to getting location of user based on WiFi network, gcm cell or ip address.
When need use only IP based way then required configuration CORS on your web server.

Send the right XMLHttpRequest header

I'm trying to make the a great wifi chip (esp8266) to communicate with a HTML webpage.
Therefore I make use of XMLHttpRequest. I know that I have to set the Access-Control-Allow-Origin to let it work..
I still get the error in the console:
XMLHttpRequest cannot load http://x.x.x.x:8000/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
So the wifi module is sending this header:
WIFI MODULE RESPONSE
HTTP/1.1 200 OK\r\n
Access-Control-Allow-Origin: *\r\n
Content-Type: text/html\r\n
Hello world!\r\n
Then I'm trying to acces it with the webpage:
JAVASCIPT
var xmlhttp;
function loadXMLDoc(){
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
console.log("readystate " + xmlhttp.readyState);
console.log("status " + xmlhttp.status);
console.log(xmlhttp.getAllResponseHeaders());
console.log(xmlhttp.responseText);
if (xmlhttp.readyState==4 && xmlhttp.status==200){
console.log(xmlhttp.responseText);
//document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://192.168.1.101:8000",true);
xmlhttp.send();
//console.log("status " + xmlhttp.status);
}
function send() {
xmlhttp.send("jooooo");
}
loadXMLDoc();
Sorry but it's not possible to give an example, because it's running locally.
Maybe someone can give me a debug method?
Update
I'm able to watch the headers in Chrome. The \r\n is displayed in the header. I can send a 200 or 404 status. But now I have to find out how to send the return statement.
View HTTP headers in Google Chrome?
So in my chrome console I get the header:
"200 OK\r\n\r\nOrigin: test\r\nAccess-Control-Allow-Origin: *\r\n\r\nContent-Type: text/html\r\n\r\nHello world!\r\n\r\n"
With a normal page I see 200 OK. So the \r\n is not working.... I have to find out how to send the return statement. When I set the 200 to a 404, I get a page not found. So the first part is received...
Ok, I removed the \r\n chars.
I just send the headers with the serial communication separate.
I succeed in sending:
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Type: text/html
And the response will be loaded in the javascript..

sending email via XMLHttpRequest no response

I tried to manage editing the template but I'm still not able to send email, I'm creating an subscription box, here's my code so far:
var x= document.getElementById("emailtxt").value;
var uploadFormData = new FormData();
uploadFormData.append("email", x);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://realfashionstreet.com/Emailme.php',true);
xhr.onload=function() {
alert(this.status);
if(this.status==200) {
console.log('data sent');
alert(xhr.responseText);
} else {
//alert(this.status);
alert('Something Went Wrong, Try Again Later!');
}
};
/*xhr.addEventListener("load", function () {
document.getElementById('skm_LockPane').className= 'LockOff';
}, false);*/
xhr.send(uploadFormData);
return false;
}
Here's the box I'm getting :
http://realfashionstreet.com
It's just not showing any error or any response and also not sending email, but I think that site template doesn't allow to use php files if anyone have any other idea on how to send email using javascript…
Thanks
You can't for security reasons. See the same origin policy for JavaScript.
There are some workarounds that exploit browser bugs or corner cases, but using them is not recommended.
The best approach is having a server-side proxy that receives Ajax requests, and in turn, sends HTTP requests to other servers. This should be carefully implemented by sanitizing input and whitelisting the types of requests that are sent, and the servers that are contacted.
You're missing the www. in the request, this is causing a cross domain policy violation. This is the error I see in the console.
XMLHttpRequest cannot load http://realfashionstreet.com/Emailme.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.realfashionstreet.com' is therefore not allowed access. Default.asp:1
Ensure the URLs for the page and the XHR request have the exact same domains. Including subdomains like www

JavaScript error when trying to fire simple XMLHttpRequest (GET)

Bit of a JavaScript newbie here -
I am firing this basic bit of JavaScript code from my website as a test:
var req = new XMLHttpRequest();
req.open('GET', 'http://www.google.co.uk/', false);
req.send();
if (req.status == 200) {
alert(req.responseText);
}
and I keep getting the following error:
[Exception... "Component returned
failure code: 0x80004005
(NS_ERROR_FAILURE)
[nsIXMLHttpRequest.send]" nsresult:
"0x80004005 (NS_ERROR_FAILURE)"
location: "JS frame ::
http://localhost/testEx3/Default.aspx
:: SendRequest :: line 402" data: no]
Does anyone know what I'm doing wrong here?
UPDATE:
OK - so what I'm actaully trying to do is a POST request to a web service I published on my local dev machine - I was getting the same error as above - that's why I put that example for simplicity. It now appears the "Same Origin Policy" has come into play - so now I have published the web service with the begining part of the URI as http://localhost/ instead of http://tempuri.org/.
Now I get a 500 error. Is there something I am missing in the headers?
var request = new XMLHttpRequest();
request.open("POST", "http://localhost/ApplicationServices.asmx?op=AddressSearch", false, "", "");
request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
request.send(x, y, buffer);
if (request.status == 200) {
alert("Success");
}
else {
alert("Failure: " + request.status);
}
It looks like you're trying to send a request that would violate the same origin policy.
Basically, in terms of AJAX requests, you're limited to sending requests to the same domain as the page sending that request. For example:
http://foo.com/bar -> http://foo.com/ajax (OK)
http://foo.bar.com/ -> http://foo.bar.com/biz/buzz (OK)
http://foo.com -> http://google.com (NO)
http://foo.bar.com -> http://biz.bar.com (NO)
You're trying to do #3 above.
If you need to send a cross-domain request, you can using JSONP or something like flensend/flxhr.
Unless you work for Google, that's not going to work. You can't pull information from another domain via XMLHttpRequest. It's called the "same origin policy".
edit — If you're getting a 500 error from your local server, that means that your HTTP request is making it to the server, and the some code in the server is failing. Check your server logs.

Categories