cfwheels 1.4.x: How to enable CORS for all requests? (via AJAX request)

138 views
Skip to first unread message

mrjayviper

unread,
Jun 10, 2021, 11:45:45 AM6/10/21
to CFWheels
Hi everyone,

We are moving the frontend of an Coldfusion/cfwheels application to the enterprise-wide CMS (Java-based and customizable) but want to keep the Coldfusion API. Keeping the API in Coldfusion/cfwheels would saves us development time.

In Controller.cfc, I placed this in the init function
    cfheader( name="Access-Control-Allow-Origin", value="*");

In my custom controller, I placed this in the init function
    Super.init();

As a test, I tried these:
  1. AJAX-request via jQuery in a static HTML file: I cannot get it to work. Firefox keeps on saying CORS needs to be enabled (I cannot tell you the exact message but I hope I conveyed the results correctly). As a test, I tried regular and private-browsing. Same results.

  2. If I entered the URL in a Firefox tab, I have no problem getting a response and I can see " Access-Control-Allow-Origin" is set to "*".
Any ideas what I could be doing wrong?

Thanks

Tom King

unread,
Jun 10, 2021, 11:53:14 AM6/10/21
to CFWheels
Your init() function is the wrong place to put CFheader as it will only fire once.

CORS was properly put in in 2.x, but if you would like a "quick hack", then add this to your /events/onrequeststart.cfm


    cfheader( name="Access-Control-Allow-Origin" value="*" );
    cfheader( name="Access-Control-Allow-Methods" value="GET, POST, PUT, PATCH, POST, DELETE, OPTIONS" );
    cfheader( name="Access-Control-Allow-Headers" value="Authorization, Origin, Content-Type, X-Auth-Token, X-Requested-By, X-Requested-With" );
    // Also for CORS compliance, an OPTIONS request must return 200 and the above headers. No data is required.
    if (
        StructKeyExists(request, "CGI")
        && StructKeyExists(request.CGI, "request_method")
        && request.CGI.request_method eq "OPTIONS"
    ) {
        abort;
    }

Reply all
Reply to author
Forward
0 new messages