Restangular crossdomain request. What I do wrong?

Deadly 提交于 2020-01-01 09:38:10

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/22526903/restangular-crossdomain-request-what-i-do-wrong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!