4

In my custom component, I have a controller to receive requests from external sites, desktop and mobile applications, the returned data in JSON format.

I encounter CORS (Cross-origin resource sharing) issue if the request is made from web application (using AngularJS), so I want to set Access-Control-Allow-Origin header to enable CORS.

However, setting header("Access-Control-Allow-Origin: *") only solves the problem if it is put in the index.php in Joomla's root folder. It doesn't take effect if it is in the controller (mycontroller.json.php). I only want Access-Control-Allow-Origin takes effect in my controller only, not the whole website.

Asking my end-users to edit their's index.php or edit .htaccess file is not a good solution at all, they are not technical users and when they update Joomla their customizations are gone.

If you have any idea to solve this CORS issue or there is any way to handle this kind of task, please let me know. I really appreciate. Thanks!

1

1 Answer 1

4

This is most likely because your coffee PHP header() call is conflicting with what Joomla has already set in the framework. Try setting using core Joomla methods:

jimport('joomla.environment.response');
JResponse::setHeader('Access-Control-Allow-Origin:', '*');

In addition, have you confirmed the core AJAX functionality is working by testing request on same domain?

5
  • Yes it works on the same domain. I tried your suggestion but it didn't work for me, I still got the same CORS error in browser's console.
    – Hung Tran
    Nov 20, 2014 at 3:58
  • The second line should be JResponse::setHeader('Access-Control-Allow-Origin', '*');
    – Hung Tran
    Nov 20, 2014 at 4:07
  • @Hung Tran Thanks for pointing that out, updated answer to reflect proper syntax. That being said, did it work? Nov 21, 2014 at 1:42
  • It also didn't work. I've solved my CORS issue by switching to JSONP although I don't like JSONP much, but at least it works and everybody is happy. However I still want to know if there is possible way to override Joomla's default headers in a specific controller.
    – Hung Tran
    Nov 21, 2014 at 3:34
  • I just noticed something which might help. The controller name being mycontroller.json.php is probably "hard" setting the header. Try renaming it to mycontroller.raw.php and the url param format to raw from json. This configuration might allow you to do CORS. Also, to prevent breaking your existing functionality, you can have both a json and raw controller version together without worry of them interfering with each other. Nov 21, 2014 at 5:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.