What is wrong with my HTTP over AJAX (javascript) - 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.

Related

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error while the header is given

I'm trying to get informations from a SystemLinkServlet.
So I tried to execute this JavaScript code from a Nintex Forms (Sharepoint) :
var http = new XMLHttpRequest();
var url = 'www.exampleservlet.com';
var params = "anyxml"
http.open('POST', url, true)
http.setRequestHeader('Content-type', 'application/xml');
http.setRequestHeader('Access-Control-Allow-Origin', '*');
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
};
http.send(params);
But I still got this error in my console :
Access to XMLHttpRequest at 'www.exampleservlet.com' from origin 'www.exampleorigin.com' 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.
It seems that the header is ignored or maybe I can't set multiple request headers?
It works on Postman.
Update
So It worked with an extension but apparently, I can't set headers with JavaScript code in my Nintex Forms.
I'm trying to find to pass those headers without using an extension.
If you are using PHP, try adding the following code at the beginning of the php file:
If you are using localhost, try this:
header("Access-Control-Allow-Origin: *");
If you are using external domains such as server, try this:
header("Access-Control-Allow-Origin: http://www.webiste.com");
Also you I suggest you to use this extension:
https://chrome.google.com/webstore/detail/cors-unblock/lfhmikememgdcahcdlaciloancbhjino?hl=en
Postman or other similar tools provide you development environments. In this way, you can ignore and pass CORS rule while sending request and getting response by changing tool settings. But if you sending request via browser(chrome, firefox etc.), browsers always add some preflight controls.
For example, browser send options message to get server side rule before your http request. So that invalid or wrong requests are blocked by browser before processing your http request.
In your case, server side must include your domain information. You can not change this communication rule from client side by adding just "Access-Control-Allow-Origin: *" or "Access-Control-Allow-Origin: http://www.webiste.com" statements.

No 'Access-Control-Allow-Origin' header is present on the requested resource - Angular 5

I'm trying to access web service from my angular service with cross-origin related headers set. But still, I'm not able to access the web service. The browser keeps saying,
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403.
I'm able to access the same URL in the browser (chrome) and postman but not in angular application.
private headers = new HttpHeaders()
.set('Access-Control-Allow-Origin', '*')
.set('Content-Type', 'application/json;charset=UTF-8')
.set('Access-Control-Allow-Headers', '*')
.set('Access-Control-Allow-Methods', 'GET, OPTIONS');
public getData(): Promise<Object> {
return this._http.get(this._url, {headers: this.headers})
.toPromise()
.then(response => {
return response;
}
)
.catch(testService.handleError);
}
Is there anything I'm missing here...
There are multiple ways to solve this issue, but first you will need to identify the extra request header parameter that is getting send by the client, if any.
It's earlier to spot this by using any of the broswer's developer console. Another pointer is to check the response/error for options call if any.
Once identified, you will need to enable the appropriate response parameters from the server, in your case it seems the options call is not setting Access-Control-Allow-Origin in the response.
Let me know if this helped you diagnose your issue.
Try JSONP. Basically as per WC3Schools states
JSONP is a method for sending JSON data without worrying about cross-domain issues.
JSONP does not use the XMLHttpRequest object.
Here's an explanation of how JSONP works
So, there is two approaches
If you have an access to edit the web service.
You need to allow Cross Origin Resource sharing.
if u are using Node.js here is an example of code to add
// ~ Cross origin resource sharing ~ //
var cors = require('cors');
// ~ Initialize the app ~ //
var app = express();
// ~ Enbling CORS ~ //
app.use(cors());
You can add a browser extension that enables you fix CORS errors for the angular app while running on browser.
Here is for chrome https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en
Here is for Mozilla https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/
You can read more at https://enable-cors.org/
I hope that helps. If there is any error let me know through comments.

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 =)

Same origin policy violation but data gets send

I'm on writing a little tracker in javascript. This tracker just gets the currently visited website with all needed informations. It also tracks ajax events. The counterpart is a java program which is hosted on the same machine as the webserver, but listening to a different port. My javascript program should not be able to send the data, because of the same origin policy (different port). The console in chrome tells me that:
XMLHttpRequest cannot load http://127.0.0.1:8082/posts. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8081' is therefore not allowed access.
What i don't get is, the data gets sent to the server! I double checked this on different machines (with different ip's). I just want to understand why. I did not write the send method on my own, thats why i don't really get it.
//sending data to server-tracker
function sendData(data)
{
console.log("Sending data: ");
console.log(data);
var xhr = window.XMLHttpRequest
? new window.XMLHttpRequest()
: window.ActiveXObject
? new ActiveXObject('Microsoft.XMLHTTP')
: null;
xhr.open('POST', "http://127.0.0.1:8082/posts", true);
xhr.send(data);
}
Thanks for helping.
The Same Origin Policy primarily stops JavaScript from reading data from other origins.
It has some features which prevent sending data to other origins under some circumstances. These can be summed up as "when the request couldn't have been constructed using an HTML form". These trigger a preflight request asking for permission to send the actual request.
Cross Origin Request Forgery which is a different problem and one best solved by using a Synchronizer Token (which is stored in HTML documents on the site (so it can only be sent by requests initiated from that site) and in the user's session (which is used to compare submitted ones).

response not getting with the header in javascript

I'm new to AJAX and I have the following code:
function get_filesize(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("HEAD", url, true);
xhr.onreadystatechange = function() {
if (this.readyState == this.DONE) {
callback(parseInt(xhr.getResponseHeader('Access-Control-Allow-Credentials')));
}
};
xhr.send();
}
get_filesize("http://fileraja.com/download/?songURL=./Tamil/K/Kaththi_160kbps/Pakkam_Vanthu-StarMusiQ.Com.mp3", function(size) {
var estimatedtime = (new Date().getTime())/size;
var time = new Date(estimatedtime);
console.log(time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds());
});
When I run this code, I get an error like:
XMLHttpRequest cannot load http://fileraja.com/download/?songURL=./Tamil/K/Kaththi_160kbps/Pakkam_Vanthu-StarMusiQ.Com.mp3. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
After some research, I have found that it's due to the CORS policy, so I tried adding the code xhr.setRequestHeader("Access-Control-Allow-Credentials",true);, but it didn't help me.
How can I get rid of this error?
After some search i have found that its due to CORS policy...so i have tried adding the code...
You can't do anything client-side that will change the CORS policy of the server. This is the point of the SOP and CORS: The server determines whether to allow any particular client to grab its content via ajax.
So unless http://fileraja.com are willing to add the relevant CORS headers at their end, you simply cannot do cross-origin requests to their domain with ajax. You might ask them, or ask if they offer a JSONP API (JSONP isn't subject to the SOP, because it's not ajax). Otherwise, you'll have to use a server of your own to proxy the request.
This error is because of the CORS(Cross Origin Resource Sharing) Policy which does not allow requests that do not arise from the same origin. A header Access-Control-Allow-Headers: * can be set at the resource to allow all requests.
Other methods include JSONP as mentioned by T.J Crowder and the same server for proxy request.
This might be a good read CORS and POST Request

Categories