0

I tried million of different examples I found on the internet.

But I still can't do it :(

Here is my REST controller:

<?
namespace app\controllers\admiral_api;

use yii\rest\Controller;

class MainPageController extends Controller {

    public function actionIndex() {
        return 'test';
    }

}
?>

I figured out I need to enable this 'Access-Control-Allow-Origin' via CORS filter on server side with Yii2. And it still doesn't work no matter what I tried.

Do you have any examples that work for you in this situation? Thank you!

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
  • Does this answer your question? [CORS header 'Access-Control-Allow-OrigCross-Origin Request Blocked yii2](https://stackoverflow.com/questions/39233893/cors-header-access-control-allow-origcross-origin-request-blocked-yii2) – Heretic Monkey Dec 11 '20 at 13:52

1 Answers1

1

You need to add Origin in Controller behaviors method.

public function behaviors() {
        return [
            'corsFilter' => [
                'class' => \yii\filters\Cors::className(),
                'cors' => [
                    // restrict access to
                    'Origin' => (YII_ENV_PROD) ? [''] : ['http://localhost:3000', 'http://your.store.com'],
                    // Allow only POST and PUT methods
                    'Access-Control-Request-Method' => ['GET', 'HEAD', 'POST', 'PUT'],
                    // Allow only headers 'X-Wsse'
                    'Access-Control-Request-Headers' => ['X-Wsse', 'Content-Type'],
                    // Allow credentials (cookies, authorization headers, etc.) to be exposed to the browser
                    'Access-Control-Allow-Credentials' => true,
                    // Allow OPTIONS caching
                    'Access-Control-Max-Age' => 3600,
                    // Allow the X-Pagination-Current-Page header to be exposed to the browser.
                    'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
                ],
            ],
        ];
    }
Akram Hossain
  • 390
  • 1
  • 10