craftcms / element-api

Create a JSON API/Feed for your elements in Craft.
MIT License
498 stars 57 forks source link

Missing "HeaderHelper"? #46

Closed fredrik-sogaard closed 7 years ago

fredrik-sogaard commented 7 years ago

I'm trying to add some CORS headers to my endpoint (ref #4 ), but I can't use the "HeaderHelper" as it looks like it isn't present in Craft 3 helpers? Is there another way if settings headers for endpoints?

At the top:

use craft\elements\Entry;
use craft\helpers\UrlHelper;
use craft\helpers\HeaderHelper;

And the relevant part where I'm trying to set the header:

    'api/work/<slug:{slug}>.json' => function($slug) {
      HeaderHelper::setHeader([
        'Access-Control-Allow-Origin' => 'http://example.com'
      ]);

Error thrown: Class 'craft\helpers\HeaderHelper' not found

Using Craft 3 Beta 18 and Element API plugin 2.4.0

brandonkelly commented 7 years ago

In Craft 3 you would do it like this:

\Craft::$app->response->headers->set('Access-Control-Allow-Origin', 'http://example.com');
jcuffney commented 6 years ago

@brandonkelly where in the request would that call go? I have the following which is not working.

<?php

use craft\elements\Entry;
use craft\helpers\UrlHelper;

return [
    'defaults' => function() {
       \Craft::$app->response->headers->set('Access-Control-Allow-Origin', 'http://example.com');
    },
    'endpoints' => [
        'news.json' => [
            'elementType' => Entry::class,
            'criteria' => ['section' => 'news'],
            'transformer' => function(Entry $entry) {
                return [
                    'title' => $entry->title,
                    'url' => $entry->url,
                    'jsonUrl' => UrlHelper::url("news/{$entry->id}.json"),
                    'summary' => $entry->summary,
                ];
            },
        ],
    ]
];
brandonkelly commented 6 years ago

Set your news.json endpoint to a function and you can put the header call at the top of it. The function should return the full endpoint config array.