GET JSON with XMLHttpRequest - javascript

I have a python script which generates a JSON and I can see it in http://192.168.1.171:17000/
In the Network tab I get
200 GET / 192.168.1.171:17000 json transfereed 40KB
When I'm trying to GET it from another webpage with javascript
var url = "http://192.168.1.171:17000";
var Httpreq = new XMLHttpRequest();
function Get(url){
Httpreq.open("GET", url, false);
//Httpreq.setRequestHeader( 'Access-Control-Allow-Origin', '*');
Httpreq.send(null);
return Httpreq.responseText;
}
var json_obj = JSON.parse(Get(url));
console.log("data: "+json_obj);
in the network tab I get
200 GET / 192.168.1.171:17000 json transfereed 0KB
it's Response tab
SyntaxError:
JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
and in the console
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help http://xhr.spec.whatwg.org/
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.1.171:17000/. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
NS_ERROR_FAILURE:
When I add
Httpreq.setRequestHeader( 'Access-Control-Allow-Origin', '*');
instead of fixing the problem I'm getting one more error
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.1.171:17000/. (Reason: CORS request failed).
When I visit http://192.168.1.171:17000/ I'm getting my json, which is valid, and when I run my javascript code with another json it runs. But when I run my javascript code with my json it doesn't run. Could you please help me to understand what I'm doing wrong here?

That header needs to be added to the server's response, not the client's request. In other words, you need to modify your Python app to return the Access-Control-Allow-Origin header. (How exactly you do that depends on what you're using on the Python side.)

Related

REST API Post request on single HTML page [duplicate]

This question already has answers here:
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 2 years ago.
I am trying to submit a post request using an endpoint URL. I am sending the content-type as application/json and two header values for username and password. When I try to access it via Postman, I get 200 response code along with tokenId and successUrl but when the same is being done via the below JavaScript code, I get 401. The same is working when I try to get is done via JSP and Java. Me, not being a Javascript expert, am unable to figure out the reason. I read the CORS articles and am not sure why cross-domain is not a problem with Java/JSP code but occurs for JavaScript.
Below is the code:
<!DOCTYPE html>
<html>
<body>
<h2>REST</h2>
<button type="button" onclick="myFunc()">Request data</button>
<p id="demo"></p>
<script>
function myFunc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "Endpoint URL entered here", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.setRequestHeader("X-OpenAM-Username", "username entered here");
xhttp.setRequestHeader("X-OpenAM-Password", "password entered here");
xhttp.send();
}
</script>
</body>
</html>
The error that comes on Chrome browser is as below:
Access to XMLHttpRequest at 'Endpoint URL' from origin 'null' 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.
a.html:23 POST 'Endpoint URL' net::ERR_FAILED
EDIT1:
The error that comes on Firefox browser is as below:
XHROPTIONS 'Endpoint URL'
[HTTP/1.1 401 Unauthorized 2025ms]
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at 'Endpoint URL'. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at 'Endpoint URL'. (Reason: CORS request did not succeed).
Please let me know what exactly am I doing wrong.
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
As part of CORS, your browser will send what’s called a 'preflight request' to the server to see if it will accept your request. It’s checking for a few things— in this case, the server didn’t reply to the preflight with the 'Acess-Control-Allow-Origin' header, so your browser knows the request you’re trying to send will fail and blocks it from being sent.
This doesn’t happen outside of the browser environment— Postman doesn’t care if the server will respond with the appropriate headers or not.
If you have access to the server, you’ll need to configure a CORS policy that allows requests from your specific origin (website). Happy to help if you can provide a little more info about your set up.

Get/examine headers of some website in console

So, I want to send a GET request from my FFQuantum console and examine the response (the header) that I receive as response. I just want to check the fields, nothing more.
Now, when I run this script on this website (https://stackoverflow.com/), with this code:
var req = new XMLHttpRequest();
var web_adress = 'https://stackoverflow.com/';
req.open('GET', web_adress, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
alert(headers);
I get the header just right, but when I'm for example, on Google, then I get the error:
For results, I expect to see filled popup but I get the empty one. That is for when I'm on Google and trying to fetch the Stack's header.
What am I getting?
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at https://stackoverflow.com/. (Reason: CORS
header ‘Access-Control-Allow-Origin’ missing).
Is there a way to get the headers from StackOverflow when I'm on Googles pages?
No, you can't. Is is because of security. Browser don't allow you to send requests across domains! To allow this action stackoverflow must return something like this:
Access-Control-Allow-Origin: https://google.com
But there isn't this header in response. If you want to do something like this - try to use special browsers which do not use The Same Origin Policy or some other soft.
Phantomjs for example or nodejs (if you want to do it with JS) or curl request etc.
But probaby you can do something like this:
google.com => yourdomain.com => stackoverflow.com
Here you use your host like a proxy (remember that you need to set Access-Control-Allow-Origin: *)
The problem is in browser security =)

Sending request to website using Javascript

i am trying to send an HTTP request to specific website and i am facing error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.google.com/. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
say for instance that i want to send request to Google.com and receive the HTML response.
my code was written using JQUERY AJAX:
function sendRequest(URL) {
$.ajax({
type:'GET',
url:URL,
success:function(result){console.log(result);}
});
}
Maybe it can help you : https://cloud.google.com/storage/docs/cross-origin#Troubleshooting%20CORS-Related-Problems
Look this one also : Access-Control-Allow-Origin error sending a jQuery Post to Google API's

CORS error in JS (XMLRequest)

I’m trying to communicate a web page with a RestAPI server. When I try to do an http request the following message appears:
XMLHttpRequest cannot load https://(MyUrl). Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
xhr.setRequestHeader("Access-Control-Allow-Origin", "*"); //Some line in my web page code
response.setRequestHeader("Access-Control-Allow-Origin", "*"); //Some line in my APIRest code
I have been doing some research about CORS and I don't understand which headers I have to include to the http request and what headers I have to include in the server to enable it. Should I add something in some .config?
For what I have understood, my petition is a “not-simple” request, as it’s a multipart request with an application/json part that also sends a token into the header. It’s a POST request.
Thanks!
It does not help that you set the headers in the client side. The server needs to have that header present in order to allow requests from third parties.
And so this will not work for you as long as the server does not have the Access-Control-Allow-Origin header set to allow your requests.
You can read more about CORS here.

What is wrong with my HTTP over AJAX (javascript)

My code:
var answer_array = [];
var req = new XMLHttpRequest();
req.onload = function() {
answer_array = answer_array.concat(JSON.parse(this.responseText).results);
console.log(answer_array);
}
req.open("GET", "https://api.comettracker.com/v1/gpsdata?fromdate=2015-10-13");
req.setRequestHeader("authorization", "Basic Base64 encoded credentials");
req.setRequestHeader("cache-control", "no-cache");
req.setRequestHeader("postman-token", "b94725ff-408b-c82e-a985-6c38feb380af");
req.send();
This is what is in my console:
scripts2.js:22 OPTIONS https://api.comettracker.com/v1/gpsdata?fromdate=2015-10-13 (anonymous function) # scripts2.js:22
2015-10-21 12:41:09.059 index.html:1 XMLHttpRequest cannot load https://api.comettracker.com/v1/gpsdata?fromdate=2015-10-13. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 405.
When I go to the network tab on Chrome I see this:
gpsdata?fromdate=2015-10-13 OPTIONS 405 xhr scripts2.js:22 0 B 452 ms
This error message:
No 'Access-Control-Allow-Origin' header is present on the requested resource
means that you are running into a cross origin permission issue which means that you are trying to access a site that does not permit access from the domain that your page is on. If your page is on your local drive being accessed with a file:// URL, then the first thing you can do is to put it on an actual web server and try it there since file:// URLs have some additional restrictions on them.
If that doesn't work either, then the issue is that the api.comettracker.com site is not allowing access from your particular site.
When I put your code into a jsFiddle and try it there and look at the network trace, what I see there is that the OPTIONS method which is used to pre-flight a cross origin request is being rejected by api.comettracker.com which tells the browser the cross origin request as currently formatted is not permitted.
I get a different error if your custom headers are removed from the request so I think that there's something incorrect about your custom headers. Since I don't know that particular API, don't have your access credentials or know how to use them, I don't know what exactly to suggest for the headers, but I think that's the place to start.

Categories