I am having trouble submitting to an API when using IE 11. I believe the problem is the API is returning TWO Access-Control-Allow-Headers in IE 11. In Chrome and Firefox, it only returns one. Also, the Access-Control-Allow-Origin returns a URL in IE 11, but returns a * in Chrome and FF. Any help in resolving this issue would be greatly appreciated as I have spend double digit hours trying to resolve with no success. The logic of what happens after submit is based on the response, but it is kicking out with errors on IE so that logic never gets executed ( SEC7123: Request header content-type was not present in the Access-Control-Allow-Headers list. - SCRIPT7002: XMLHttpRequest: Network Error 0x80070005, Access is denied. ).
IE 11 Response Headers:
Access-Control-Allow-Headers bearer_token
Access-Control-Allow-Headers authorization, x-date, Content-Type, if-none-match
Access-Control-Allow-Origin - https://this.that.com
Chrome and FF Response Headers (the ones that are different from IE):
Access-Control-Allow-Headers - authorization, x-date, etag, content-type, range, if-none-match
Access-Control-Allow-Origin - *
Code being used to submit:
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$("#ajaxform").submit(function(e)
{
$.ajax({
url: 'https://this.that.com?firstname=test&lastname=test&email=test55#n2.com',
dataType: 'json',
type: 'post',
contentType: 'application/json',
data: '{}',
xhrFields: {
withCredentials: true
},
headers: {
'Authorization': 'Bearer XXXXXXXXXXXXXXXXXXXXXXXX'
},
success: function( data, status, jQxhr ){
var thisResponse = jQxhr.responseText;
var trimResp = thisResponse.slice(2, -2);
thisParse = jQuery.parseJSON(trimResp);
var thisStatus = thisParse.status;
console.log(jQxhr);
//alert(thisStatus);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log("readyState: " + jqXhr.readyState);
console.log("responseText: "+ jqXhr.responseText);
console.log("status: " + jqXhr.status);
console.log("text status: " + textStatus);
console.log(jqXhr.getAllResponseHeaders);
}
});
e.preventDefault();
});
Thanks for taking the time to read through this.
Cheers~
C
Related
I am trying to consume a mercadolibre API that returns a json with some data that I need to use.
But everytime I tried by an ajax GET request it returns the same error:
"Response to preflight request doesn't pass access control check: It does not have HTTP ok status"
I Think it is a CORS issue, but I have tried everything on headers while the request (which is corssed domain) and nothing seems to work.
Here is the way I am doing the ajax request:
if (obtieneCotizaciones == 'true' && token != null) {
var sellerID = '499777238';
$.ajax({
type: "GET",
url: "https://api.mercadolibre.com/quotations?access_token="+token+"&seller.id="+sellerID+"&caller.type=seller",
contentType: "application/json",
headers: {
'Access-Control-Allow-Credentials' : true,
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods':'GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS',
'Access-Control-Max-Age': '604800',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Headers':'application/json',
'Access-Control-Allow-Headers': 'x-requested-with'
},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error)
console.log("FAIL");
}
});
}
Any Idea how could I solve this? don't mind for 'token' and 'obtieneCotizaciones' variables, they are just needed to make the request and I obtein them before doing the request.
Have you tried removing all of the headers? They are triggering a pre-flight which is why it's failing with that error.
I'm setting encrypted username and password authorization in fron end and getting request header response bearer authorization from server. In ajax i'm getting to get that response header in safari correctly but in chrome and firefox its like a null. The problem only in chrome and firefox to get bearer token. How to fix that issues?
Ajax code,
$.ajax({
type:"POST",
url:url,
dataType: "json",
async:false,
headers:{
'Authorization':'Basic '+btoa(useremail+":"+password)
},
data:'{"datas"}',
success: function (data, status, request, xhr){
alert(request.getResponseHeader('Authorization'));
}
Note that as of jQuery 1.8 async option is deprecated.
As to why this probably happens:
During a CORS request, the getResponseHeader() method can only access
simple response headers. Simple response headers are defined as
follows:
Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma
And as for the solution:
If you want clients to be able to access other headers, you have to
use the Access-Control-Expose-Headers header. The value of this header
is a comma-delimited list of response headers you want to expose to
the client.
Source: https://www.html5rocks.com/en/tutorials/cors/
With reference from this articel : http://osric.com/chris/accidental-developer/2014/08/using-getresponseheader-with-jquerys-ajax-method/
Try with done function as shown in the example in the article :
$.ajax({
type:"POST",
url:url,
dataType: "json",
async:false,
headers:{
'Authorization':'Basic '+btoa(useremail+":"+password)
},
data:'{"datas"}',
}).done(function (data, textStatus, xhr) {
console.log(xhr.getResponseHeader('Authorization'));
});
try this..
var settings = {
"crossDomain": true,
"url": url,
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded",
"Authorization":"Basic "+btoa(useremail+":"+password)
},
"data": {
"name": "name"
}
}
$.ajax(settings).done(function (data,status, xhr) {
console.log("Authorization=> "+xhr.getResponseHeader('Authorization'));
});
I have an Ajax request on a domian xyz.com and I am performing an
Ajax request from xyz.com to pull data from abc.xyz.com
var request = $.ajax({
type: "POST",
url: "https://abc.mno.com/vending/mainvending.php",
data: {vlu:"1"},
dataType: 'json',
timeout: 10000,
crossDomain: true,
async: true,
cache: false,
headers: { "cache-control": "no-cache" },
error: function( jqXHR, textStatus, errorThrown )
{
alert("error : " + errorThrown + " text :"+textStatus + " j :" +jqXHR.status);
// alert(jqXHR.responseText);
},
success: Succeeded,
beforeSend: function( xhr ) { }
});
but I keep getting this error which is consoled out in the browser (Chrome)
XMLHttpRequest cannot load https://abc.xyz.com/vending/mainvending.php. Request header field cache-control is not allowed by Access-Control-Allow-Headers in preflight response.
In the mainvending.php the codes are as follows
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
require_once 'vendors.php';
if(!empty($_POST)){
/** Other codes follow **/
}else{
/** Other codes follow **/
}
?>
what am I not doing or what am I doing wrong? The domain name is xyz and the domain I am retrieving data from is of a sub domain could that be the issue and how do I go around this.
Your error message says that the server isn't allowing you to send a cache-control header.
You are doing that here:
headers: { "cache-control": "no-cache" },
… cache-control is a response header, so it makes no sense to include it in a request.
Remove that line.
(Alternatively, you could add it to the Access-Control-Allow-Headers header that you are already setting).
You can do one of the following two things:-
Remove this key-value pair from your AJAX config
headers: { "cache-control": "no-cache" },
Add cache-control header to your PHP code to allow it.
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, cache-control');
Try setting these headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
I have built a client application, that uses Ajax to call a WebService on another domain (the server supports CORS).
Sometimes when Ajax makes the preflight call, it gets a http error code 400 or 500 from the server, and a response in the format:
{
"httpStatus": 400,
"statusCode": 400
}
I can see the error in the browsers console, but in my JavaScript code, I just get status 0 and statusText "error". Does anyone know how to retrieve the output from the preflight call in JavaScript?
My Ajax call looks lige this:
$.ajax({
type: method,
xhrFields: { withCredentials: true },
url: url,
cache: false,
data: data || '',
contentType: 'application/json; charset=UTF-8',
dataType: 'json',
beforeSend: function(r) {
r.setRequestHeader('Authorization', 'Bearer ' + oauthtoken);
r.setRequestHeader("X-Client-Version", "0.0.1");
}
}).success(function(response) {
console.log("success - service " + url);
callback(response);
}).fail(function(response, textStatus, errorThrown) {
console.log("fail - service " + url);
callback(response);
});
I am trying to call Neo4j API from jquery.
when i am invoking GET requests it works perfectly
GET request endpoint
http://localhost:7474/db/data/node/10
but when i am invoking POST requests with json body it returns following error.
POST request endpoint
http://localhost:7474/db/data/cypher
Error Message
"NetworkError: 500 Server Error - http://localhost:7474/db/data/cypher"
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:7474/db/data/cypher. This can be fixed by moving the resource to the same domain or enabling CORS.
When i try from Advance REST Client, it returns correct response. Please refer following code
$(document).ready(function(){
$("#btnQuery").click(function(){
var Request = "{'query' : 'MATCH (Movie { name:{searchName} })-[SHOWS]-(Cinema) RETURN Cinema','params' : {'searchName' : 'Rio 2'}}";
//url = mainURL +"cypher";
url = "http://localhost:7474/db/data/cypher";
$.ajax({
url: url,
headers : {
'Authorization' : 'Bearer 5f0e0d8c2a5477d4a8e79fa2d34f84a'
},
crossDomain: true,
type: 'POST',
dataType: 'application/json',
complete: function(xhr) {
if (xhr.readyState == 4) {
if (xhr.status == 201) {
alert("Data is loaded");
clearUsers();
isUserAdd = false;
}
} else {
alert("Data is not loaded");
}
},
beforeSend: function (xhr) {
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
data: ('(' + Request + ')')
});
});
});
I have a working example here: http://jexp.github.io/cy2neo
Check out the code: https://github.com/jexp/cy2neo/blob/master/scripts/neo.js#L8
I think the problem was dataType: JSON which caused jquery to send a pre-flight header w/o CORS. I changed it to specifying content-type: JSON