Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restangular crossdomain request. What I do wrong?

I have domain sub.example.com with configured restangular:

RestangularProvider.setDefaultHeaders({
    'Content-Type': 'application/json',
    'X-Requested-With': 'XMLHttpRequest'
});
RestangularProvider.setDefaultHttpFields({
    'withCredentials': true
});

Then I'm building other factory via:

return Restangular.withConfig(function(RestangularProvider) {
    RestangularProvider.setBaseUrl('http://api.example.com');
});

And, obviously, getting error No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://sub.example.com' is therefore not allowed access.. How should I configure server/client to get working crossdomain requests?

// upd

I'm using Yii on backend and sending next header
header('Access-Control-Allow-Origin: *', true);

like image 344
Miraage Avatar asked Mar 20 '14 08:03

Miraage


Video Answer


1 Answers

I've found solution.

At first, when using credentials - we can't use * for Access-Control-Allow-Origin. Then, XHR sends OPTIONS request that should be handled well and send CORS headers.

// scheme required, here can be multiple origins concatenated by space if using credentials
header('Access-Control-Allow-Origin: http://sub.example.com');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: Accept, X-Requested-With');
// without credentials we can use * for origin
header('Access-Control-Allow-Credentials: true');
header('HTTP/1.1 200 OK', true);

Then we can simply use crossdomain ajax requests.

like image 80
Miraage Avatar answered Sep 19 '22 02:09

Miraage