Chromes security stops me from sending emails, would android also stop it? - javascript

I'm making a Cordova app. I have an email sending function, when i test my app in chrome i get the following error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I have looked through out stack overflow and havent been able to find a solution. Nothing ive seen has worked. Some people say this problem is specific to chrome and other browsers. If its only browsers that are the problem when i run my app on android everything should be fine and the email should send, right? Heres the code if you wanted to see:
var message = localStorage.getItem("Message");
var key = "xxthisisakeyxx";
var message_name = "send_message";
var data = {};
data.value1 = message;
data.value2 = localStorage.getItem("AdminsEmail");
var url = "https://example.com/trigger/" + message_name + "/with/key/" + key;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
console.log("Message Sent");
console.log(JSON.stringify(XMLHttpRequest));
}
}
}
xmlhttp.open('POST', url, true);
xmlhttp.setRequestHeader( 'Access-Control-Allow-Origin', "http://localhost:8000");
xmlhttp.setRequestHeader( 'Content-Type', 'application/json' );
xmlhttp.responseType = 'json';
xmlhttp.send(new FormData(data));
Thank you

The problem would be the access-control on the server side script.
Example: If you are posting the data to a php script you may need to include this line at the top of the .php file:
header('Access-Control-Allow-Origin: *');
This can be unsafe but if you are posting the data from inside a Cordova app it may be hard to specify an exact origin.

Related

Getting the CORS policy: No 'Access-Control-Allow-Origin' error

I am trying to integrate a third party API using JavaScript and its working fine on local but it is showing the error on live i.e.
Access to XMLHttpRequest at 'https://newsapi.org/v2/top-headlines?country=in&category=technology' from origin 'https://www.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Here is my JavaScript,
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj, i, x = "";
myObj = JSON.parse(this.response);
for (i=0;i<1;i++ in myObj.articles) {
x += "<a href="+ myObj.articles[i].url +" target='blank'>";
x += "<div style='background: linear-gradient(rgba(0,130,170,0),rgba(6,23,0,1)), url( "+ myObj.articles[i].urlToImage +" );height: 430px;margin-top: 20px;'>";
x += "</div>";
x += "</a>";
}
document.getElementById("technology").innerHTML = x;
}
};
xmlhttp.open("GET", "https://newsapi.org/v2/top-headlines?country=in&category=technology", true);
xmlhttp.send();
HTML
<div style="background-color: gray;height: 430px;margin-top: 20px;">
p id="technology"></p>
</div>
I don't understand why this is happening.
Please help me out,
Thanks in advance.
The response is right in front of your eyes - You need to pay to use it outside of "localhost" domain which usually means you are develeping the site as developer thus you use the "Developer" plan. But when going live you need to pay up:
And you clearly missing the API Key (if you havent cut it out to paste here;) ) in the request ;)
As mentioned by #chris-g you are not using api-key. You might try with API key and perhaps CORS issue would be gone.
If you are still getting CORS, try simple jquery $ajax with jsonp or try a simple proxy server to forward the request and response.
var proxy_url = 'https://cors-anywhere.herokuapp.com/';
var url = 'https://newsapi.org/v2/top-headlines?country=us&category=sports&pageSize=5&apiKey=<your-api-key>';
Now you can you use the proxy_url to avoid the CORS policy error by adding the proxy_url in front of your URL with the API-KEY
new_url = proxy_url + url

Issue with JSON.parse() from URL

I have this code trying to obtain prices from Bloomberg but I can't make it works.
This is the URL:
https://www.bloomberg.com/markets2/api/intraday/BACHOCOB:MM?days=1&interval=2&volumeInterval=15
And my failure code:
<p id="quote"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var price= JSON.parse(this.responseText);
document.getElementById("quote").innerHTML = price[0]["previousClosingPriceOneTradingDayAgo"];
}
};
xmlhttp.open("GET", "https://www.bloomberg.com/markets2/api/intraday/BACHOCOB:MM?days=1&interval=2&volumeInterval=15&currency=MXN", true);
xmlhttp.send();
</script>
Thanks in advance.
What is the excat error message your getting? Is it something like "No 'Access-Control-Allow-Origin' header is present on the requested resource"?
If so, that has nothing to do with JSON.parse as it is a security measure against XSS (Cross Site Scripting). You cannot request web responses from other domains if the server doesn't allows it explicitly.
See https://en.wikipedia.org/wiki/Cross-origin_resource_sharing for more information.
As an additional note: you can work around this. Even if you have no access to the server you could make use of a proxy server, that gets the request for you and uses the appropriate response header to allow your script to make the response. An example would be "corsproxy" from npm (No experience with it. Just a quick google search).
You can get value as below by adding jQuery to your project
$.ajax({
type: "GET",
url: "https://www.bloomberg.com/markets2/api/intraday/BACHOCOB:MM?days=1&interval=2&volumeInterval=15",
dataType: "json",
success: function(getPrice) {
$('#quote').append(getPrice[0].previousClosingPriceOneTradingDayAgo);
}
});
It seems CORS is an issue. Since you are using GET request to an SSL URL, it expects you to send this request from an HTTPS origin. To test your script, use Chrome Browser with CORS extension installed. You shall see the result.
In short, you need an HTTPS origin URL, you might want to try CURL with PHP for a possible solution if SSL is an issue !

Cross-domain post to external site fails on wordpress

I'm trying to post data to an external website from a wordpress site using Javascript, however when i send the form i'm getting this:
XMLHttpRequest cannot load https://external_site.com/embed/documents.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://my_site.com' is therefore not allowed access.
The response had HTTP status code 404
I'm trying to this from a Wordpress site, this is the Javascript part that sends the data
jQuery('#send_doc').click(function(){
var url = jQuery('#document_url').val();
var name = jQuery('#name').val();
var request = new XMLHttpRequest();
request.open('POST', 'https://external_site.com/embed/documents');
request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Authorization', 'Token my_token
request.onreadystatechange = function () {
if (this.readyState === 4) {
console.log('Status:', this.status);
console.log('Headers:', this.getAllResponseHeaders());
console.log('Body:', this.responseText);
}
};
var body = {
'document_url': url,
'name': name
};
request.send(JSON.stringify(body));
});
My question is, i understand that this is a Cross-domain problem, but my question is: Can i resolve the problem by my side or is this problem just on the externa site side?
Thank you very much for your answers

Setting CORS headers does not work in Chrome, Firefox or on mobile browser

I am trying to consume a third party's response. Its working fine in IE but not working in Chrome, Firefox or on my mobile browser. I google and tried some codes but still facing same issue. I know its CORS error and there are lots of references or tutorials are available, I want to know why my code is not working, whats the error?
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.<third_party_sitename>.com/json/feeds?system=" + abc);
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, HEAD");
xhr.setRequestHeader("Access-Control-Allow-Headers", "X-Requested-With");
xhr.setRequestHeader("Access-Control-Max-Age", "1728000");
//xhr.setRequestHeader("Connection", "Keep-Alive");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
var datax = JSON.stringify(this.responseText);
var jsonObj = jQuery.parseJSON(datax);
displayPin(jsonObj);
}
};
xhr.send(null);
Access-Control-Allow-Origin and co are response headers. The server you are making the request to (api.<third_party_sitename>.com) has to set them in the response.
They are not request headers. Your JavaScript can't give itself permission to read data from arbitrary third party sites.

XMLHttpRequest and Web Workers Access-Control-Origin

I'm dealing with some Access-Control-Origin issues when using webworkers to make an XMLHttpRequest.
The issue is easily reproducible in this code, main.js:
var worker = new Worker('js/createSimplePage.js');
worker.onmessage = function () {
console.log('message recieved');
};
And js/createSimplePage.js:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
console.log(xmlhttp.responseText);
}
};
xmlhttp.open("GET", "http://search.twitter.com/search.json?q=balling&rpp=20&callback=", true);
xmlhttp.setRequestHeader('Content-Type', 'text/plain');
xmlhttp.send();
If I include createSimplePage.js in the header of index.html, it runs fine and prints the correct response from the twitter API. However, if I only load main.js and let it try to load createSimplePage.js as a web worker then I receive the error:
XMLHttpRequest cannot load http://search.twitter.com/search.json?q=balling&rpp=20&callback=.
Origin file:// is not allowed by Access-Control-Allow-Origin.
A similar error occurs when hosting the files on SimpleHTTPServer except the error is then
"Origin http://127.0.0.1:8000 is not allowed by Access-Countrol-Allow-Origin."
I don't understand why loading it as a web-worker would break it so it can't access the API.
I don't think webworkers have the same security level as the browser. Maybe you could ensure you scripts are returned with allow all origins header:
header("Access-Control-Allow-Origin: *");
and probably best to removed your custom header:
xmlhttp.setRequestHeader('Content-Type', 'text/plain');
This site has more information:
http://enable-cors.org/

Categories