CORS not allowing jquery AJAX get results - javascript

I am calling an AJAX function in my script from a server of IP - 128.119.30.12:7080 (for example)
Cross Domain: port number are different, so I get error of incompatibility.
$.ajax({
url: "http://128.119.30.12:9000/callback.php",
data: dataObj,
type: "POST",
contentType: 'text/plain',
sucess: function(data,status){
reply = data;
},
error : function(xhr, status, error){
reply = {"error": "Error in fetching data"}
}
}).done(function(reply) {
replyCall(reply);
});
function replyCall(data) {
console.log(data);
}
I have enabled the mod_header function in my Apache server. And setting up header in the called php script - here is the script of php
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
print 'Hellooooooooo Response';
?>
It is still causing errors on chrome -
XMLHttpRequest cannot load http://128.119.30.12:9000/callback.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://128.119.30.12:7080' is therefore not allowed access.

Related

API get cross domain issues - Cross-Origin Read Blocking (CORB)

I'm trying to use API to get information about a specific user based on user ID. I need to use basic auth and pass some headers with my call.
I'm getting this:
Cross-Origin Read Blocking (CORB) blocked cross-origin response "rest/user/getProfile?callback=jQuery224033348109431646855_1548684613983&userId=24068..." with MIME type text/plain.
My code:
$.ajax
({
type: 'GET',
crossDomain: true,
async: false,
url: 'example_URL_/api/user/getProfile',
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
},
beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", "Basic ZHVubmVzYXBpskjoi43u5409543o9tI654kjhugjy"); },
dataType: 'jsonp',
data: { "Id": "1234" },
success: function (data) {
console.log(data);
},
error: function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
}
});
is there anything I'm missing?
You said:
dataType: 'jsonp',
… so jQuery makes a JSONP request (i.e. inserts a <script> element).
The browser makes a request to the URL and the server said:
Content-Type: text/plain
Since a plain text document is not a JavaScript program, the browser refused to execute it and threw a CORB error instead.
A JSONP response must be application/javascript, not text/plain.
You need to either:
Not make a request for JSONP
Change the server to respond with JSONP
Aside: Since you are using JSONP, the type, crossDomain, async, headers, and xhr.setRequestHeader properties have no effect.
Since you said you needed to set basic auth, that rules out option two. You can't use JSONP for this.
In your API configure CORS to accept all domains, or enter the domain that you're using to send the request from.
If your API is created by PHP here is an example:
<?php
header("Access-Control-Allow-Origin: *");
Or if you are using a third party API, try to see the documentation. I'm sure there will be a part talking about CORS.

$.ajax requests with CORS

I'm having troubles with an AJAX request. I was getting the below error:
Error: Access is denied
I tried this jQuery AJAX request:
$.support.cors = true;
$.ajax({
url: 'http://testwebsite.com/test',
type: "GET",
dataType: 'json',
contentType: 'application/json',
crossDomain: true,
headers: {
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Origin': 'http://testwebsite/test',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Credentials': 'true'
},
xhrFields: {
withCredentials: true
},
success: function(data) {
alert("Data from Server" + JSON.stringify(data));
},
error: function(jqXHR, textStatus, errorThrown) {
alert("You can not send Cross Domain AJAX requests: " + errorThrown);
}
});
Can anyone kindly let me know what I am missing. Thanks in advance.
As rory-mccrossan mentioned in a comment, CORS protection is designed so that a website cannot directly access the content of another website (in a browser) unless the website being accessed agrees to it.
It would completely ruin the point of CORS if a site just has to send some headers in order to circumvent the defence
Instead, you will need to use a CORS proxy. It's a server that when given a request like yourCORSproxy.example.com/http://testwebsite/test would load the page and return it, but with CORS allowed (like a normal proxy but with CORS enabled).
One of these CORS proxies is https://crossorigin.me, but at the time of writing this it is down. It might be more stable if you simply create your own proxy.
tl;dr: testsite.test should be sending the headers on its response. You should not be sending the headers on your request.

AWSELB Cookie access from Javascript

I having problems to access the "Set-Cookie" header where AWSELB id is stored in order to set it for the subsequent requests.
I thought it was a problem with CORS configuration so i tried:
cors.headers = [
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Headers': 'origin, authorization, accept, content-type, x-requested-with, X-Auth-Token, Set-Cookie, set-cookie',
'Access-Control-Expose-Headers': 'Set-Cookie, set-cookie'
]
cors.allow.origin.regex = '.*'
cors.expose.headers = 'Set-Cookie, set-cookie'
In the server side.
I can see all those CORS headers in the response, still when i try to getAllResponseHeaders from client side i cannot see "Set-Cookie" neither i can get specific header by name.
I am missing something?
I've check this in both Chrome and Firefox
EDIT1: This is my JS side
$.ajax({
url: url,
type: "POST",
cache: false,
crossDomain: true,
data: JSON.stringify(dataMock),
dataType: "text",
contentType: "text",
success: function(response, textStatus, jqXHR) {
if (jqXHR.getResponseHeader('Set-Cookie')) {
document.cookie = jqXHR.getResponseHeader('Set-Cookie');
}
}
});
};
Cookies are explicitly excluded from getResponseHeader and getAllResponseHeaders:
client . getAllResponseHeaders()
Returns all headers from the response, with the exception of those whose field name is Set-Cookie or Set-Cookie2.
client . getAllResponseHeaders()
Returns all headers from the response, with the exception of those whose field name is Set-Cookie or Set-Cookie2.
If you want to access them directly from JS then you must change the server so that it duplicates the information in them elsewhere in the response.

add header in ajax for Cross-Origin, not working

When I add header HTTP_X_REQUESTED_WITH in ajax for request to another server then it give erorr as Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.xxxxxxxxxxxx.com/checkurl.php?action=xxxxxxx. This can be fixed by moving the resource to the same domain or enabling CORS.
and if I remove this header it working properly.
I have many ajax request so I use this format to add header in all ajax request
$(document).ajaxSend(function (event, jqxhr, settings) {
jqxhr.setRequestHeader('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest')
});
and my ajax is :
$.ajax({
url:sitePath+'Xxxxxxxxx/checkurl.php?action=Pages&page='+actionPage,
type :'POST',
crossDomain:true,
success : function(data){
hideLoadingDiv();
if(data.getElementsByTagName("message")[0].getElementsByTagName("messageType")[0].childNodes[0].nodeValue=="SUCCESS")
{
document.getElementById(divID).innerHTML=data.getElementsByTagName("PageBody")[0].childNodes[0].nodeValue+'<span><a onclick="return checkRegistrationValidation();" href="javascript:void(0);" class="orengeBtn">Back</a></span>';
displayDiv(divID);
}
else if(data.getElementsByTagName("message")[0].getElementsByTagName("messageType")[0].childNodes[0].nodeValue=="ERROR")
{
showErrorMessage(data.getElementsByTagName("message")[0].getElementsByTagName("messageText")[0].childNodes[0].nodeValue);
}
else
{
generalError();
}
},
error:function(xhr,ajaxOptions, thrownError){
hideLoadingDiv();
if(xhr.status==200){
generalError();
}
else{
networkError();
}
if(debugMode==1){
displayAjaxError(xhr,thrownError);
}
}
});
and in my server file I use
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: X-Requested-With, Content-Type')
but it give error every time when I add header. And after remove working properly. Please help.
You can find answer here:
Cross-Domain AJAX doesn't send X-Requested-With header
You have to either add the headers manually in your ajax:
$.ajax({
url:sitePath+'Xxxxxxxxx/checkurl.php?action=Pages&page='+actionPage,
type :'POST',
crossDomain:true,
headers: {'X-Requested-With': 'XMLHttpRequest'}
or make the request not crossdomain:
$.ajax({
url:sitePath+'Xxxxxxxxx/checkurl.php?action=Pages&page='+actionPage,
type :'POST',
crossDomain:false,

setRequestHeader not working, I want to set my header and then make a GET request in ajax in Amazon EC2

I am trying to make a GET request and for this I am supposed to send header values, I Have tried the methods below. This API call seems to be working fine in POSTMAN extension I use to test the API's
$.ajax({
url: "requested url",
type: 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader('setHeader', '12345');
},
success: function (data) {
console.log(data);
},
error: function () {
alert("Failed");
},
});
AJAX request seems to be working fine, but the moment I add a header via beforeSend or headers, an OPTIONS pre-flight request is made and the GET request is aborted.
I have also tried setting the headers using $.ajaxSetup();
$.ajaxSetup({
beforeSend: function (xhr) {
xhr.setRequestHeader('setHeader', '12345');
}
});
$.ajax({
type: "GET",
url: "requested url"
}).success(function (data) {
console.log(data);
}).error(function () {
alert("Failed");
});
Request headers :
Request URL:requested url
Request Method:OPTIONS
Status Code:404 Not Found
Request Headersview source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, setHeader
Access-Control-Request-Method:GET
Response headers :
Access-Control-Allow-Headers:Content-Type, Accept, X-Requested-With,setHeader
Access-Control-Allow-Method:GET,POST,PUT,OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Expose-Headers:*
I get this error in my console :
XMLHttpRequest cannot load "requested url". Invalid HTTP status code 404
Maybe your problem is jsonp related. Just guesing here.
what-is-jsonp-all-about
can-i-set-headers-in-cross-domain-json-requests
Check your server headers aswell.

Categories