He always throws this error at me:
Access to XMLHttpRequest at ‘https://developer.apirest.company/web/siat/unidad-medida’ from origin ‘http://localhost:5173’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.
ServiceModule.php
<?php
namespace app\modules\service;
use sizeg\jwt\JwtHttpBearerAuth;
use Yii;
use app\modules\service\behaviors\JwtBehavior;
use app\modules\service\components\TokenValidationBehavior;
/**
* service module definition class
*/
class ServiceModule extends \yii\base\Module
{
public $controllerNamespace = 'app\modules\service\controllers';
public function init()
{
parent::init();
Yii::$app->user->enableSession = false; // Desactivar sesión
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; // Establecer formato JSON
}
public function behaviors()
{
$behaviors = parent::behaviors();
// Agregar autenticador y comportamientos
$behaviors['authenticator'] = [
'class' => JwtHttpBearerAuth::class,
];
$behaviors['tokenValidation'] = TokenValidationBehavior::class;
return $behaviors;
}
}
BaseController.php
<?php
namespace app\modules\service\controllers;
use Yii;
use yii\rest\ActiveController;
use yii\web\Response;
use yii\filters\Cors;
/**
* Base controller for service module
*/
class BaseController extends ActiveController
{
private $dbUser;
private $dbPassword;
private $dbHost;
public function __construct($id, $module, $config = [])
{
// Configuración de conexión a la base de datos
$this->dbUser = Yii::$app->params['dbUser'];
$this->dbPassword = Yii::$app->params['dbPassword'];
$this->dbHost = Yii::$app->params['dbHost'];
parent::__construct($id, $module, $config);
}
public function behaviors()
{
$behaviors = parent::behaviors();
// Configuración CORS
$behaviors['corsFilter'] = [
'class' => Cors::class,
'cors' => [
'Origin' => ['http://localhost:5173', 'http://127.0.0.1:8000', $_SERVER["REMOTE_ADDR"]],
'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
'Access-Control-Allow-Credentials' => true,
'Access-Control-Allow-Headers' => ['authorization', 'X-Requested-With', 'content-type'],
'Access-Control-Max-Age' => 3600,
'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page', 'X-Pagination-Page-Count'],
],
];
return $behaviors;
}
public function beforeAction($action)
{
Yii::$app->response->format = Response::FORMAT_JSON; // Establecer el formato de respuesta a JSON
return parent::beforeAction($action);
}
// Método para retornar el tipo de respuestas
protected function sendResponse($response)
{
Yii::$app->response->statusCode = $response['statusCode'];
return [
'message' => $response['message'],
'name' => $response['name'] ?? null,
'errors' => $response['errors'] ?? null,
'data' => $response['data'] ?? null,
];
}
}