Restangular crossdomain request. What I do wrong?
Asked Answered
G

1

6

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);

Gunshy answered 20/3, 2014 at 8:6 Comment(1)
Your server-side header doesn't seem to be correct: the key and value pair are both in the key side - so the mapping doesn't mean anything. (Access-Control-Allow-Origin, "*") see enable-cors.org/server_apache.htmlExciting
G
6

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.

Gunshy answered 28/3, 2014 at 5:19 Comment(5)
Thanks for the follow up. I am encountering the exact same issue.Groveman
@ChuckConway np. Glad to see that my answer helped somebody.Gunshy
Very lost with how do I set this?Theoretician
I'm guessing this is some API side PHP.Cumulus
@AJ_83 anywhere in your backend before any headers are sent.Gunshy

© 2022 - 2024 — McMap. All rights reserved.