5

First Craft project and off to a great start. I don't think i'll ever touch Wordpress again. :)

I'm using the Element API plugin to build out one of my feeds of entries and hoping to use that on a couple sites as a little widget.

JSON: https://csgoevents.gg/api/events.json

Using jQuery for now: http://codepen.io/eboyer/pen/kXqNXJ

Getting this error: "XMLHttpRequest cannot load . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is therefore not allowed access."

Historically, i'm more of a designer/html/css developer, so HTTP & API work is new to me. From what I understand this can be avoided if the server could return JSONP? Or if I had any sort of control over nginx configurations? (I'm hosting with Web Faction)

Are there any examples out there of using Element API data on other domains?

Hopefully its something with a quick solve. Thanks in advance, excited to be here!

3

Brandon answered this in a github issue https://github.com/pixelandtonic/ElementAPI/issues/4

You can do that by setting your endpoint config to an anonymous function:

'my/endpoint/pattern' => function() {
    HeaderHelper::setHeader([
        'Access-Control-Allow-Origin' => 'http://example.com'
    ]);

    return [
        // ...
    ];
}
2

I don't know whether you've seen this answer to another similar question, but it might get you a bit closer:

Ajax Post to guestEntries/saveEntries from another domain

You could maybe combine what the answer says with the {% header %} tag to output the two headers mentioned in the answer.

You could always tailor the Access-Control-Allow-Origin to be more specific to your setup if you don't want open up access to all domains. You can find more information on the Headers themselves here :

Mozilla Developer Network: HTTP access control (CORS)

(About half way down the page where it explains what Lines 13 - 22 in the example are doing).

I haven't used the Element API myself yet, so all this may be way off, but hopefully it'll point you in the right direction!

EDIT: As you're using WebFaction, you should have access to add/edit the .htaccess file for you site, so you might be able to add those headers straight in there. There's more info in their docs here:

Webfaction: Static Files, CGI Scripts, and PHP Pages

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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