Cross origin blocking despite subdomain exists in policy - ajax

Hello I am trying to use cross origin from a subdomain (app.example.com) to www.example.com. When I try to execute the ajax I receive this:
XMLHttpRequest cannot load http://app.example.com/. The 'Access-Control-Allow-Origin' header has a value 'http://app.edentalbook.com' that is not equal to the supplied origin. Origin 'null' is therefore not allowed access.
I dont understand how I should use it..In my apache conf file I have those lines in order to enable cross origing policy:
Header always set Access-Control-Allow-Origin "http://app.example.com"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding"
Header always set Access-Control-Allow-Credentials "true"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
My ajax call:
$.ajax({
method: "GET",
url:'http://www.example.com/index.php?logout',
crossDomain: true,
dataType: "json",
xhrFields: {
withCredentials: false
},
success: function(data){
loginPresta(email,password,companyName);
if(data == 'ok') {
}
},
error:function(data){
}
});

Related

sending data as json from ajax to express server causes preflight cors error

This question has been asked a gazillion times. I've read the mozilla documentation and looked through so many answers my eyes hurt.
In my ajax call I have this:
$.ajax({
type: 'POST',
dataType: 'json',
data: {name: "test"},
contentType: 'application/json',
url: 'https://example.com:8443',
success: function (data) {
alert(data);
}
in my express server my server.js file is this:
app.post('/', function (req, res) {
console.log(req.body.myData);
res.header('Access-Control-Allow-Origin: *');
res.header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
return res.end('<h1>Hello, Secure World!</h1>');
});
from my understanding I'm properly making the ajax call with dataType: 'json', and contentType 'application/json'.
Also I'm setting acess control allow origin to * which should allow me to have any domain hit my server. I can't figure out what I'm doing wrong. I get this error:
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.
Any help would be appreciated!
My error was a dumb one. In express js this is incorrect:
res.header('Access-Control-Allow-Origin: *');
res.header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
The settings should actually be like this '','' not ':'
The correct syntax that worked is this:
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
EDIT: Using * is a security risk but in this case it's one server testing on another both of which I own. When going live I would set * to example.com

How to use ajax in reactjs on localhost

Below is my code:
While using local url I am getting the error
"Failed to load http://localhost/reactjs/my-app/lib/ajax.php: 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:3000' is therefore not allowed access"
But when I used live url such as "https://jsonplaceholder.typicode.com/todos" its working fine.
$.ajax({
url: 'http://localhost/reactjs/lib/ajax.php',
//url: 'https://jsonplaceholder.typicode.com/todos',
type: 'GET',
dataType: 'jsonp',
//contentType: "application/json; charset=utf-8",
//jsonp: "json_callback",
crossOrigin: true,
//cors: true,
//data: {user_name:username, user_type: usertype, password: password,mode: 'Login' },
success: function(data){
alert(data);
},
error: function(error){
console.log(error);
}
});
You are calling different host so that's why you have CORS issue. Your application is running on localhost:3000 and you are calling your service on localhost.
You can do what Vivek suggests (if it is different host) or you just need to have proper port referenced (if both applications are on localhost:3000).
Note that you don't have to write absolute url in ajax. Instead, if it is on same host, you could just write /reactjs/lib/ajax.php.
Add this on php side :
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
And this url http://localhost/reactjs/my-app/lib/ajax.php should be http://localhost/reactjs/lib/ajax.php

Ajax: GET call to api on Cross subdomain

I am trying to make ajax call to my crm api using this code but cant get this work without errors:
var username = 'admin';
var password = '1';
$.ajax
({
type: "GET",
dataType: 'json',
async: false,
url: "http://demo.espocrm.com/basic/api/v1/App/user",
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)
}
})
.done(function(){
alert('Authenticated!')
})
.fail(function(){
alert('Error!')
});
the call come from www.domain.com to crm.domain.com
in the .htaccess on crm.domain.com i have this code:
<ifModule mod_headers.c>
Header set Access-Control-Allow-Origin "http://www.domain.com"
Header set Access-Control-Allow-Methods "OPTIONS, GET, PUT, POST, DELETE, HEAD"
Header set Access-Control-Max-Age "1800"
</ifModule>
I also tried to use jsnot and use this url: http://demo.espocrm.com/basic/api/v1/App/user?callback=?
the errors are:
OPTIONS http://crm.domain.com/api/v1/App/user?_=1437237158381 500 (Internal Server Error)
XMLHttpRequest cannot load http://crm.domain.com/api/v1/App/user?_=1437237158381. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.domain.com' is therefore not allowed access. The response had HTTP status code 500.
when i use jsnop:
GET http://crm.domain.com/api/v1/App/user?callback=jQuery21404605716757941991_1437238651212&_=1437238651213

Cross domain ajax hits error even that the status came back is 200

I am sending cross domain ajax request, the response comes back with status 200. I also see that the request arrives to the server.
I have this in my server:
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
context.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
context.Response.Headers.Add("Access-Control-Allow-Headers", "*");
This is on the client:
$.ajax({
type: "POST",
url: this.SERVER + url,
data: data,
xhrFields: {
withCredentials: true
},
success: function (a, b) {
debugger;
alert("sdsd");
},error : function(a,b) {
debugger;
},
dataType: 'json'
});
this is the request from the chrome browser
In firefox its I get the error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:2000/PageHandler.ashx. This can be fixed by moving the resource to the same domain or enabling CORS
My wild guess is that since you are sending the Access-Control-Allow-Credentials header you cannot put * in Access-Control-Allow-Origin. Try specifying the origin as that of your JavaScript client.
I am basing this on the following piece of information from the Mozilla Developer Networks Documentation on CORS:
The origin parameter specifies a URI that may access the resource.
The browser must enforce this. For requests without credentials, the
server may specify "*" as a wildcard, thereby allowing any origin to
access the resource.

Can't retrieve my x-api-key from my request header with CORS enabled. Why?

I'm working with CodeIgniter2 Rest API and AJAX to make requests from a smartphone with PhoneGap to a AWS server with apache.
Everything was working fine when working on my localhost/browser.
But when trying to set up a distant server things got bad.
I have configured my server properly with CORS so that it allows external requests as explained here :
http://dev.nuclearrooster.com/2011/01/03/cors-with-apache-mod_headers-and-htaccess/
To secure the API, I have been setting up an API KEY that I have to pass in the header of my request like so:
$.ajax({
type:"GET",
url: server_url + 'user/available',
headers: { 'X-API-KEY': key },
dataType: 'json'
});
But then, after seeing my ajax called being refused because of an invalid API Key, I have been trying to make sure the server received the key. and it doesnt. when I try to echo my key, its empty.
I can see in my debug console the following:
Request header field X-API-KEY is not allowed by Access-Control-Allow-Headers.
So I have been modifying my .htaccess following this post:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type, x-api-key"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
so now, the message is gone but the problem still remains the same ... why ?
How can I transmit this X-API-KEY through my AJAX call Header so I can authentificate my users ?
Many Thanks
I faced this problem and with weeks of tweaking I was able to get it to work with a hack of a job... I can't remember the exact part that did fix it but will provide with what I am currently using.
Server Side
function __construct(){
parent::__construct();
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("Access-Control-Allow-Headers: X-API-KEY");
}
function available_options(){
$this->response(array('response' => array()), 200);
}
Client Side
function sendData(dataToSend, successCallback) {
window.default_headers['X-API-KEY'] = '_KEY_';
return $.ajax({
type: "POST",
url: server_url + 'user/available',
data: { data : JSON.stringify(dataToSend) }, // serializes the form's elements.
dataType: 'json',
headers: window.default_headers,
xhrFields: {
withCredentials: true
}
});
}
Since you're using a GET request, possibly using JSONP would be of more use, this avoids cross domain requests.
JSONP Request
$.ajax({
type : "GET",
dataType : "jsonp",
url: server_url + "user/available?callback=?", // ?callback=?
success: function(data){
// do stuff with data
}
});

Resources