Answer the question
In order to leave comments, you need to log in
How to bypass CORS in POST/DELETE requests in Yii2?
Front on Vue.js. Trying to send post or delete - CORS error.
I send GET - everything is fine, what kind of magic????? How can I send a POST?
Access to XMLHttpRequest at 'http://192.168.99.101:8000/api/v1/items/7' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
public function beforeAction($action)
{
$this->enableCsrfValidation = false;
return parent::beforeAction($action);
}
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::class,
'cors' => [
// restrict access to
'Origin' => ['*'],
// Allow methods
'Access-Control-Request-Method' => ['POST', 'PUT', 'OPTIONS', 'GET', 'DELETE'],
// Allow only headers 'X-Wsse'
'Access-Control-Request-Headers' => ['*'],
'Access-Control-Allow-Headers' => ['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' => ['*']
],
];
return $behaviors;
}
Answer the question
In order to leave comments, you need to log in
EMNIP, for all requests except GET, the browser performs CORS Preflight . Before the main request, OPTIONS is sent, in response to which the browser expects to receive a 200 code and set Access-Control headers.
https to both domains. Cross domain requests, if my memory serves me right on http does not work.
Check that your server accepts all types of GET POST OPTIONS requests
/**
* @inheritdoc
*/
public function behaviors()
{
$behaviors = parent::behaviors();
unset($behaviors['authenticator']);
// Добавляем первоначально CORS!
$behaviors['corsFilter'] = [
'class' => Cors::class,
];
// Теперь авторизацию.
$behaviors['authenticator'] = [
'class' => HttpBearerAuth::class,
'except' => ['options'],
];
return $behaviors;
}
The browser writes that the Access-Control-Allow-Origin header is missing, add it to the config to yii\filters\Cors. Or take it to the server settings.
And inherit from yii\rest\Controller, and not from yii\web\Controller - the code will be cleaned from unnecessary redefinitions.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question