Yii2 api CORS error It does not have HTTP ok status

Hello,

i would need help about CORS with yii2.
I have an app that works fine, on yii2 advanced template.
I need to add an api for a part of it, so i created a /bakcend/modules/api controllers etc.

I will add under this message my codes.

if i try to use my api with postman i can get and post without problems, but when i try with javascript,
my problem now is that i get an error :

vueform.html:1 Access to XMLHttpRequest at ‘https://MYDOMAIN/api/produits’ from origin ‘http://localhost:8888’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.

in backend/config/main.php

under components request

'parsers' => [
          'Application/json' => \yii\web\JsnoParser::class
        ]

under rules
[
   'class'=> \yii\rest\UrlRule::class,
   'controller' => ['api/produits']
],

in backend/web/index.php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, accept, authorization, Content-Type, X-Auth-Tokens, X-Requested-With');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');

backend/modules/api/controllers/ProduitsController.php

<?php

namespace backend\modules\api\controllers;
use Yii;
use yii\rest\ActiveController;
use yii\filters\auth\HttpBearerAuth;
use backend\modules\api\resources\Cors;
use backend\modules\api\resources\ProduitsResource;

class ProduitsController extends ActiveController
{
  public $modelClass = ProduitsResource::class;

public static function allowedDomains() {
  return [$_SERVER["REMOTE_ADDR"], '*'];
}

 public function behaviors()
 {
    $behaviors = parent::behaviors();
     $behaviors['authenticator']['except'] = ['options'];

     $auth = $behaviors['authenticator'];
     $auth['authMethods'] = [
         HttpBearerAuth::class
     ];

     unset($behaviors['authenticator']);
     $behaviors['authenticator'] = $auth;


    return array_merge($behaviors, [
      'corsFilter'  => [
        'class' => Cors::className(),
        'cors'  => [
          // restrict access to domains:
          'Origin'                           => static::allowedDomains(),
          'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
          'Access-Control-Allow-Credentials' => true,
          'Access-Control-Max-Age'           => 3600,                 // Cache (seconds)
          'Access-Control-Allow-Headers' => ['origin','authorization','X-Requested-With','X-Auth-Token','content-type'],
          'Access-Control-Request-Headers' => ['*'],
        // 'Access-Control-Expose-Headers' => []
        ],
      ],
    ]);

    return $behaviors;
  }

public function actions()
 {
    //  Yii::$app->response->statusCode = 200;
    $actions = parent::actions();

    // disable the "delete" and "create" actions
    //unset($actions['delete'], $actions['update'], $actions['index']);

    return $actions;
  }

}

backend/modules/api/resources/Cors.php

<?php
namespace backend\modules\api\resources;

class Cors extends \yii\filters\Cors {

public function prepareHeaders($requestHeaders) {
    $responseHeaders = parent::prepareHeaders($requestHeaders);
    if (isset($this->cors['Access-Control-Allow-Headers'])) {
        $responseHeaders['Access-Control-Allow-Headers'] = implode(', ', $this->cors['Access-Control-Allow-Headers']);
    }
    return $responseHeaders;
 }
}
?>

backend/modules/api/resources/ProduitsResources

<?php

namespace backend\modules\api\resources;
use common\models\Produits;

class ProduitsResource extends Produits
{

}

backend/modules/api/Modules.php

<?php

namespace backend\modules\api;

class Module extends \yii\base\Module
{

}

?>

And my javascript call :

jQuery.ajax( {
url: 'https://MYDOMAIN/api/produits',
type: 'POST',
data: { product_title: 'testing test' },
beforeSend : function( xhr ) {
    xhr.setRequestHeader( "Authorization", "Bearer MYTOKENSTRING");
},
success: function( response ) {
    // response
}

} );

did you solve this?

Yes thank you :slight_smile:

How you solve it
?

1 Like