Send the right XMLHttpRequest header - javascript

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..

Related

Mixed Content on XMLHttp request

I'm currently working with the Bungie API and am having some trouble getting OAuth Tokens from a POST request. I am currently using javascript with XMLHttpRequest to make the post and handle the response, but every time I send a post, it gives me a Mixed Content page even though both the website I am hosting and the API endpoint is https. I've been searching everywhere and all I can find is that I either need to secure my site (even though my site has an SSL certificate) or alter the URL in the post by removing or adding a slash (I've done both many times). Any advice or ideas are appreciated, thanks!
Code:
var url="https://www.bungie.net/Platform/App/OAuth/Token";
https.onreadystatechange = function() {
if(this.readyState==4){
if (this.status==200) {
console.log(this.responseText);
}
else if (this.status==400) {
console.error("Bad Request (400) Response: " + this.responseText);
}
else if (this.status==401) {
console.error("Unauthorized (401) Response: " + this.responseText);
}
else {
console.error("There was a Problem: " + this.responseText);
}
}
}
https.open('POST', url, true);
https.setRequestHeader("X-API-Key","e76XXXXXXXXXXXXXXXXXXX");
https.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
https.setRequestHeader("Authorization", authHeader);
https.send(data);
Error Message:
Mixed Content: The page at 'https://mywebsiteurl.com/callbacks.html?
code=08fcbde4d71019d1d795a1c1dd79be67' was loaded over HTTPS, but requested an insecure
XMLHttpRequest endpoint 'http://www.bungie.net/Platform/App/OAuth/Token/'. This request has been
blocked; the content must be served over HTTPS.
This is a problem with the bungle.net server. It's redirecting from HTTPS to HTTP, and Chrome is then blocking this because it violates the restriction against mixed content.
I don't think there's anything you can do in your code to override the restriction.

"No 'Access-Control-Allow-Origin' header is present on the requested resource." when making "GET" request

I'm using an HTTP-request in order to get Google's autocomplete suggestions, here's what inspired me to do so:
You can make a GET request to the following URL:
http://suggestqueries.google.com/complete/search?client=chrome&q=cats
Where "client" param is your browser's name (works with most but you may pass >the same type disregarding what the user is currently on and it will still work).
And "q" param is your search string.
This will return you a list of suggested items which you can then put into a jQuery autocomplete plugin or build your own (you can't just get the whole >google dropdown interface to popup with a single function sadly :) )
(src: Add Google autocomplete to Google search bar?)
I'm using this function to get Google's response text:
function httpGetAsync(theUrl, getGoogle){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
getGoogle(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
However, when the funtion is executed, CORS seems to prevent me from getting a response: Failed to load http://suggestqueries.google.com/complete/search?client=chrome&q=xx: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
Is there a way of adding an 'Access-Control-Allow-Origin' header to the resource?
You cannot make a request to another domain from the users browser, unless the source has the Access-Control-Allow-Origin header for your domain. In conclusion, you cannot make the request on the users part without using some kind of proxy, like this one:
https://cors-anywhere.herokuapp.com/
Example:
url: https://cors-anywhere.herokuapp.com/https://google.com

How to solve "Cross-Origin Request Blocked" error?

I have problem with CORS. I already search many time in google to solve this problem, but doesn't work.
I make a popup dialog procedure with external popup.js file. This js file can show popup dialog when I call that file from any page in same project(myweb.com).
But the problem is when I call this js file from another website like this,
<script type="text/javascript" src="http://www.myweb.com/admin/popup.js"></script>
<script> document.addEventListener("DOMContentLoaded", function(event) {
create_popup();
});
</script>
I get this error,
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.myweb.com/admin/get_data.php?t=0.4987759219367701.
(Reason: missing token 'access-control-allow-methods' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel).
In my js file I run get_data.php file by using ajax. Here is my js file,
function create_popup() {
var xmlhttp = new XMLHttpRequest();
if("withCredentials" in xmlhttp){
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var arr = JSON.parse(xmlhttp.responseText);
alert(arr);
}
xmlhttp.open("GET","http://www.myweb.com/admin/get_data.php?t="+Math.random(),true);
xmlhttp.setRequestHeader( "Pragma", "no-cache" );
xmlhttp.setRequestHeader( "Cache-Control", "no-cache" );
xmlhttp.setRequestHeader("Access-Control-Allow-Origin","*");
xmlhttp.setRequestHeader("Access-Control-Allow-Credentials", "true");
xmlhttp.setRequestHeader("Access-Control-Allow-Methods", "GET");
xmlhttp.setRequestHeader("Access-Control-Allow-Headers", "Content-Type");
xmlhttp.send();
}else{
alert("error");
console.log("error");
}
}
This js file is only work in myweb.com. But when I try to call this js from another website I get CORS error.
And I also add header for CORS in get_data.php file like this,
header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods:GET");
header("Access-Control-Allow-Headers:Content-Type");
header("Access-Control-Allow-Credentials:true");
But it doesn't work. I'm not sure about header declaration is ok or not in js and php file. I try a lot but I don't know how to solve.
And I already try in chrome browser with Allow-Control-Allow-Origin extensions. But I can't see popup and error. I don't know which part is wrong. I very appreciate for your suggestion.
(Reason: missing token 'access-control-allow-methods' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel).
This shows that the preflight is failing
preflight only occurs under certain conditions, one of which is when you add "custom" headers to the request
as you are incorrectly adding headers to your request (headers which only make sense as response headers anyway)
xmlhttp.setRequestHeader("Access-Control-Allow-Origin","*");
xmlhttp.setRequestHeader("Access-Control-Allow-Credentials", "true");
xmlhttp.setRequestHeader("Access-Control-Allow-Methods", "GET");
xmlhttp.setRequestHeader("Access-Control-Allow-Headers", "Content-Type");
a preflight is triggered (as they are custom headers) - your server doesn't handle (doesn't even ALLOW) preflight, hence the preflight error
Remove those setRequestHeader lines, and it should work

Cross Domain XHR failing inspite of Access-Control-Allow-Origin header

I am new to XHR and am trying to solve a simple use case. I have a web server, from where my javascript would fetch data. But instead of serving the data itself, the server would redirect the javascript XHR request to an alternate location (for example a file on Amazon's S3) to fulfill the request.
This brought me into the world of cross domain XHR, and I am unable to get even a simple example working inspite of reading a bit about it. I am adding "Access-Control-Allow-Origin: *" to the header in my main domain which serves the web page containing the javascript. But it does not work. What am I missing? I need this to work regardless of browser so am looking for something the initial server can do other than serving as a proxy, which defeats the purpose of offloading the request to S3.
Chrome : Gives "Exception: NetworkError: DOM Exception 19" on the
second call.
IE: Shows a warning but opens second url after
confirmation.
Firefox: Just says "Exception: Faliure" on the second
call.
Code follows for test.php:
<?php
header('Content-type: text/html');
header('Access-Control-Allow-Origin: *');
?>
<!DOCTYPE html>
<html>
<header>
<script type="text/javascript">
var request;
var url1 = "data/file.csv";
var url2 = "http://stackoverflow.com/users/1293955/ng-algo";
try
{
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
request = new XMLHttpRequest();
}
else {
// code for IE6, IE5
request = new ActiveXObject('Microsoft.XMLHTTP');
}
// load data. 'false' indicates that further script
// is not executed until data is loaded and parsed
alert("Test1 with url: "+url1);
request.open('GET', url1, false);
request.send();
alert(request.responseText);
alert("Test2 with url: "+url2);
request.open('GET', url2, false);
request.send();
alert(request.responseText);
} catch (e) { alert("Exception: "+e.message); }
</script>
</header>
This is a test page
</html>
For any arbitrary request (given the mix of Amazon and Stack Overflow in the question), CORS may not be enough as it's actually the remote server that has to give the permission.
For the 2nd request to succeed, stackoverflow.com would have to include relevant Access-Control-Allow-* headers in their responses that give your website permission to make the request. And whether those are included in the response or not is entirely up to Stack Exchange, in this case.
Also, by including Access-Control-Allow-Origin: * in the response, you're actually allowing other websites to request your page from their origin.
What you may need is a "proxy" script on your server. You can find a generalized solution from Ben Alman:
http://benalman.com/projects/php-simple-proxy/
https://github.com/cowboy/php-simple-proxy
Which would allow:
request.open('GET', 'proxy.php?url=' + encodeURIComponent(url2), false);

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