I'm trying to perform basic authentication for JIRA, by using JIRA's REST API.
JIRA's website does provide a CURL command to get this done:
curl -D- -u fred:fred -X GET -H "Content-Type: application/json"
http://example.com/rest/api/2/issue/createmeta
When I run this in Chrome, I'm getting the following error:
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
When I run this code in IE, I'm getting the following response, but I know using * for access control defeats the purpose CORS:
{"self":"https://mypersonaljiraurl.org/jira/rest/api/latest/user?
username=12345","name":"12345","loginInfo":
{"failedLoginCount":2,"loginCount":50}}
I wrote the following code in Javascript to make a HTTP request.
var request = new XMLHttpRequest();
request.open("GET", "https://mypersonaljiraurl/rest/auth/1/session", false);
request.setRequestHeader("Authorization", authenticateUser(userName, passWord));
request.setRequestHeader("Content-Type", 'application/json');
request.setRequestHeader('Access-Control-Allow-Origin', '*');
request.send();
alert(request.status);
response.innerHTML = request.responseText;
How do I resolve this so it can work in Chrome? Would it be better to do this with Jquery/Ajax?
Related
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.
When I run this post via curl in terminal. My test function works great. I see the name I pass as a parameter in the response inside my test lambda function. But getting it working through terminal is not my end goal unfortunately.
curl -v -X POST 'https://miyyxihee3.execute-api.us-east-1.amazonaws.com/prod/EchoTest' -H 'content-type: application/json' -d '{
"callerName": "Name!"
}'
I'm looking to call this url and post data through it via javascript. My issue is that I get a CORS related error when I attempt to make a POST call on the javascript. More specifically, the error is:
Failed to load https://miyyxihee3.execute-api.us-east-1.amazonaws.com/prod/EchoTest: 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.
Here is what I have tried in my javascript code:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST", "https://miyyxihee3.execute-api.us-east-1.amazonaws.com/prod/EchoTest");
xmlhttp.setRequestHeader('Access-Control-Allow-Methods', 'POST');
xmlhttp.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token');
xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify({callerName:"Name!"}));
P.S. I'm new to javascript. I have been poking my head in some CORS documentation. From my understanding, CORS needs specific headers to accommodate the post request? I have CORS enabled inside my AWS API gateway. A bit confused why it works in the terminal but not in javascript. Can someone kindly help?
I want to convert this cURL to angular 2 post request
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -H "Authorization: Basic cGJob2xlOmlJelVNR3o4" -H "Origin: http://localhost:4200/form" -H "Postman-Token: fbf7ede1-4648-a330-14ee-85e6c29ee80d" -d 'content=Queue: tsi-testdesk' "https://testdesk.ebi.ac.uk/REST/1.0/ticket/new?user=USER&pass=PASS"
here is the code i wrote but its not working.
addForm(form: Form): Observable<Form> {
console.log(" SUBMITTING FORM");
let headers = new Headers();
this.loginService.writeAuthToHeaders(headers);
// JSON.stringify(headers);
// headers.append('Accept', 'application/x-www-form-urlencoded');
headers.append('Content-Type', 'application/x-www-form-urlencoded');
// let text = JSON.stringify(form)
let content = ('content:Queue: tsi-testdesk');
console.log(content);
return this.http.post('https://testdesk.ebi.ac.uk/REST/1.0/ticket/new?user='+this.credentialsService.getUsername()+'&pass='+this.credentialsService.getPassword(), content, { headers: headers })
// .map(response => <Form>response.json())
.catch(this.handleError);
}
It is giving me pre-flight response fail error but it works fine with cURL as well as POSTMAN and also I Dont have access to server side I am contacting it through API
CORS is a policy that is enforced by the web browser. Ultimately, it is up to the browser, whether or not it will allow a cross-origin request. In the case of cURL or Postman, there is no browser, there is no current HOST, so there is not even the concept of a cross-origin request. Technically Postman is a Chrome extension, but it is not at all the same thing as loading a web page and making cross-origin requests.
Public-facing API's (probably like the one you are trying to access) already have CORS enabled. The likely culprit is your own server. You must enable CORS requests on your web server so it will allow you to make requests to outside APIs.
Unable to make https XMLHttpRequest requests - getting this back:
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:8443' is therefore not allowed access.
If I replace the url with www.google.com, it's fine, but https://www.google.com does the same thing.
It works when I use Postman/JaSON Chrome extensions, so I tried open -a Google\ Chrome --args --disable-web-security, but that didn't work either.
let request = new XMLHttpRequest();
request.open("POST", "https://outlook.office365.com/EWS/Exchange.asmx", true);
request.setRequestHeader("Authorization", "Bearer " + asyncResult.value);
request.setRequestHeader("Content-type", "text/xml; charset=utf-8");
request.setRequestHeader('Access-Control-Allow-Origin', '*');
request.setRequestHeader("Access-Control-Allow-Headers", "Content-type, Origin");
request.setRequestHeader("Access-Control-Allow-Methods", "POST");
request.onload = function() {
};
request.onerror = function() {
debugger;
}
request.send(requestBody);
The "Access-Control-Allow-Origin" header is set server-side for security reasons.
If you had access to the server you could just do:
header("Access-Control-Allow-Origin: *");
This, however, is not safe for obvious reasons. You should always allow as minimum external access as possible.
Recently I had the same issue. What I did was just use my own server, make the request from there to the api, and just have the script make the request to my server instead (from which you can set the access control header). So basically, instead of making the request to the third party client-side (from javascript), make it server-side and then get that data from your server via 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({}) );