Javascript CORS GET request blocked or invalid - javascript

I'm struggling for quite some time already with issuing a simple GET request to a 3rd party REST Api. I've read a bit of tutorials and SO questions but I just can't get it to work. I am getting one of two errors
Response for preflight is invalid (redirect)
or (if via https)
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:8433' is therefore not allowed access.
About 2nd message: Is it just a problem with the server not supporting CORS?
My code:
var xmlHttp = new XMLHttpRequest();
var url = 'https://inspirehep.net/record/451647?of=recjson&ot=recid,number_of_citations,authors,title'; //http or https, tried both
/*
doing sth with response here like populate dropdown etc.
*/
xmlHttp.open('GET', url, true);
xmlHttp.setRequestHeader("Access-Control-Allow-Headers", "Content-Type, X-Requested-With, Cache-Control");
xmlHttp.setRequestHeader("Content-Type", "application/json");
xmlHttp.setRequestHeader("Access-Control-Allow-Origin", '*');
xmlHttp.setRequestHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
xmlHttp.setRequestHeader("Access-Control-Allow-Credentials", "true");
xmlHttp.send();
Whole app is running on node.js server (localhost) and the script above is included as separate file in .html view.
I can correctly get json response from web-browser, fiddler, postman etc. for this API. I also tried different APIs (e.g. Openweather API) thinking that it's the problem with server configuration, but the result was the same.
I would be thankful for any help - maybe i'm just misunderstanding something about CORS.

you cannot set headers from the browser, if the target url runs on your server or a server that you manage and that server runs nodejs you can use cors https://www.npmjs.com/package/cors, however, if this is a third party url and it doesn't not allow CORS, then you should make the request from the your back-end through configuring a proxy from your server to third party server, that should resolve your problem.

The answer on CORS with nodejs is most likely right, but I want to suggest that you run a test to make sure your code works fine as well.
Try with Chrome and download an extension to allow CORS. This way you will test the functionality first before trying the right solution.

Late to the party...
http://cors-anywhere.herokuapp.com/ is great, but you don't need it if you are using XMLHttpRequest() and a GET method. Simply exclude your header requests...
var xhr = new XMLHttpRequest();
xhr.open( "GET", YOURURL );
//OMIT THESE...
//xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
//xhr.withCredentials = true;
//xhr.setRequestHeader( 'Content-Type', _contenttype );
//xhr.setRequestHeader( 'CrossDomain', 'true' );
//....
xhr.addEventListener( 'load', function () {
xhr.responseJSON = JSON.parse( xhr.responseText );
alert( xhr.responseJSON);
});
xhr.onerror = function(e) {
alert("Ajax request error");
};
xhr.send( JSON.stringify({}) );

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.

I receive a 404 HTTP error with an API using javascript but not in my terminal

I am using the Pons dictionary API documented here: https://en.pons.com/assets/docs/api_dict.pdf
It works when I use a get request in my mac terminal, but not when using XMLHttpRequest in my javascript file (shown below) when testing it in my browser. It always gives me a 404 error and then states
"Access to XMLHttpRequest at 'https://api.pons.com/v1/dictionary?q=casa&l=dees' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status."
Any ideas?
I have tried making a request that does not require my X-Secret (credentials) and it works, but as soon as I set the X-Secret header it throws a 404 error. I need to set this heading for most request types.
Here is my code. I have censored my credentials in the X-Secret header.
var request = new XMLHttpRequest()
let url = new URL('https://api.pons.com/v1/dictionary');
url.searchParams.set('q', 'casa');
url.searchParams.set('l', 'dees');
request.open('GET', url);
//request.withCredentials = true;
request.setRequestHeader("X-Secret", "***");
request.setRequestHeader("Access-Control-Allow-Origin", "*");
request.setRequestHeader("Access-Control-Allow-Credentials", "true");
request.setRequestHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
request.setRequestHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization");
request.send()
request.onload = function() {
// Begin accessing JSON data here
var data = JSON.parse(this.response)
if (request.status >= 200 && request.status < 400) {
console.log(data)
} else {
console.log('error')
}
}
CORS is "cross-origin resource sharing"; specifically, it's used to refer to policies that block requests between different domains. In this case, XHR is sending a "preflight request" -- that is, a request with verb OPTIONS (rather than GET, POST, etc.) -- to make sure the server will accept a real request. It will do this whenever you use non-standard (and some standard but optional) headers. The preflight request is coming back as 404; the server doesn't support OPTIONS to that endpoint.
The way to get around CORS is to use a proxy. That is, have a backend script (in Node, PHP, whatever) on your domain that sends the request to the other API server and echoes its response. CORS only applies to AJAX requests, not backend ones, so this will get around the issue, and it is the accepted technique.

XMLHttpRequest server responded with a status of 405 (Method Not Allowed)

I am using this HTTP POST Request code to send a json data to Couchbase bucket/document. I don't know exactly why it is throwing error as "XMLHttpRequest send Failed to load resource: the server responded with a status of 405 (Method Not Allowed)"
When I tested this, it is working fine through Postman.
var params = {
"EmpID":"567453",
"EmpAddress": "XX",
"EmpAccount": "89723",
"EmpName": "user1953977",
"EmpType": "DEV"
}
var xhr = new XMLHttpRequest();
var url = "http://xxxx:PORT/xxxx/xxx/xxx/docs/docs/firstdoc/"; // Couchbase document url
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Accept", "application/json" );
xhr.setRequestHeader("Authorization", "Basic XXXXXXXXXXXXXXXXXX");
xhr.setRequestHeader("Cache-Control", "no-cache");
var data = JSON.stringify(params);
xhr.send(data)
Can someone advise me where is the issue? Is there way a to fix?
I'm pretty sure that what you're doing is making POST requests to Couchbase Server from a browser. The 405 error you're getting is likely due to CORS. CORS cannot be turned off in Couchbase Server (unless you fork and compile yourself, I guess). Couchbase Server is not designed to be accessed directly from the browser like this.
Some options:
Couchbase Server sits behind an API and you would use the SDK of your choice (node, Java, .NET, whatever) to interact with Couchbase there.
Use Sync Gateway in front of Couchbase, which has an API that allows your to enable CORS (see Sync Gateway Public REST API documentation).
Turn off same-origin policy in your browser (like in Chrome), but this is not typically practical for most applications, as you would need every user to turn off CORS.

XMLHttpRequest fails to send cookie if progress is tracked

I've got a simple code that sends files to server from https://app.myserver:4202 to https://myserver/backend/upload.php:
//script executed on`https://app.myserver:4202`
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://myserver.com/backend/upload.php");
xhr.withCredentials = true;
xhr.send(fd); //fd is formdata from file input
yay, it successfully sends the files with cookie so I can perform user authentication in my upload.php script. Now, I also want to display progress bar so I changed the code to this:
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://myserver.com/backend/upload.php");
xhr.withCredentials = true;
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
console.log("add upload event-listener" + evt.loaded + "/" + evt.total);
}
}, true);
xhr.send(fd);
Whoa, all hell broke loose! We have a CORS problem. Notice that I only added a progress tracker.
Access to XMLHttpRequest at 'https://myserver/backend/upload.php' from origin 'https://myserver:4202' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I took great care to setup CORS correctly so this are myserver response headers that are relevant to CORS
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: origin, x-requested-with, content-type
Access-Control-Allow-Methods: DELETE, HEAD, GET, OPTIONS, POST, PUT
Access-Control-Allow-Origin: https://app.myserver.com:4202
Access-Control-Max-Age: 86400
They work well, if no progress info is desired, but fail when it is tracked.
So tell me, what am I missing out here?
We have a CORS problem. Notice that I only added a progress tracker.
This behaviour is defined in the spec:
Registering one or more event listeners on an XMLHttpRequestUpload object will result in a CORS-preflight request. (That is because registering an event listener causes the upload listener flag to be set, which in turn causes the use-CORS-preflight flag to be set.)
I took great care to setup CORS correctly so this are myserver response headers that are relevant to CORS
Read the error message carefully:
Access to XMLHttpRequest at 'https://myserver/backend/upload.php' from origin 'https://myserver:4202' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
So the HTTP response headers you set aren't really relevant.
The browser is making the OPTIONS request to ask for permission to make the POST request and the server is responding with something other that 200 OK.
Possibly it is sending 405 Method Not Allowed. Check the Network tab of your developer tools to find out exactly what the HTTP response status is, and then adjust the server accordingly.

Access-Control-Allow-Origin in http request

I am running a server on my localhost with an HTML5 application.
I would like to send an http-request to a second server "130.100.100.100:50000".
I have the following JavaScript code running on localhost where I am sending http requests to the second server.
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {}
};
xmlhttp.open("GET", "http://130.100.100.100:50000/company.html/query?a0=" + a0, true);
xmlhttp.setRequestHeader( 'Access-Control-Allow-Origin', '*');
xmlhttp.send();
The second server is receiving my queries but I don't get any answer for my request. I think the problem is that the Same Origin Policy is violated. I tried to use the CORS standard to set
Access-Control-Allow-Origin: *
But the GET requests I am sending still doesn't contain "Access-Control-Allow-Origin" in the header. If I send the request manually with "Access-Control-Allow-Origin: *" everything is working proper. Do I have a mistake in my JavaScript code? I would like to avoid using jQuery.
You need to allow cross origin on server. Follow https://ma.ttias.be/set-access-control-allow-origin-cors-headers-apache-vhost-htaccess/
You need a page used as a proxy. This page will send a GET request to the target page and display the response. Make sure that relative paths at img, a, script and link are converted to full paths. If you do this, the CORS problem will be fixed.

Categories