pro-dev
@pro-dev

Как разрешить CORS запрос для API?

Привет! Почему то не получается отправить put запрос на сервер. Выходит такая ошибка:


OPTIONS 127.0.0.1:8000/api/events/1960aaeb-5c81-471a-bd3d-... 405 (Method Not Allowed)

Access to XMLHttpRequest at '127.0.0.1:8000/api/events/1960aaeb-5c81-471a-bd3d-...' from origin 'localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.


в index.php поместил такой код:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET,POST,PUT,DELETE,HEAD,OPTIONS");
header("Access-Control-Allow-Headers: Origin,Content-Type,Accept,Authorization");
header("Access-Control-Allow-Headers: *");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Credentials: true");
    header("Access-Control-Allow-Methods: GET,POST,PUT,DELETE,HEAD,OPTIONS");
    header("Access-Control-Allow-Headers: Origin,Content-Type,Accept,Authorization");
    header("Content-Type: text/plain charset=UTF-8");
    header("Content-Length: 0");
}


но это не помогает... В чём может быть проблема? И как правильно разрешить ошибку с cors?
  • Вопрос задан
  • 5159 просмотров
Решения вопроса 1
IgorPI
@IgorPI
Используйте Nginx, выкиньте Apache
server {
    listen                          80;

    client_max_body_size            208M;
    access_log                      /var/log/nginx/secure.access.log;
    error_log                       /var/log/nginx/secure.error.log error;

    root                            /www/public;

    add_header				        "Access-Control-Allow-Origin" "*";
    add_header				        "Access-Control-Allow-Headers" "Origin, X-Requested-With, Content-Type, Accept, Authorization";
    add_header				        "Access-Control-Request-Methods" "GET, POST, OPTIONS";

    location / {
        try_files                   $uri $uri/ /secure.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_split_path_info     ^(.+\.php)(/.+)$;
        fastcgi_pass                app:9000;
        fastcgi_index               secure.php;
        include                     fastcgi_params;
        fastcgi_param               SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param               PATH_INFO $fastcgi_path_info;
    }
}
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
Yauheni85
@Yauheni85
Можно создать 2 EventSubscriber'а

На запрос:
// ...
class RequestSubscriber implements EventSubscriberInterface {

	public function onRequestEvent(RequestEvent $event) {
		if($event->getRequest()->getMethod() === 'OPTIONS') {
			$response = new Response(null);
			$event->setResponse($response);
		} 
	}

	public static function getSubscribedEvents() {
		return [RequestEvent::class => ['onRequestEvent', 5000]];
	}

}


И на ответ:
// ...
class ResponseSubscriber implements EventSubscriberInterface {

	public function onResponseEvent(ResponseEvent $event) {
		$headers = $event->getResponse()->headers;
		$headers->set('Access-Control-Allow-Origin', '*');
		if($event->getRequest()->getMethod() === 'OPTIONS') {
			$headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
			$headers->set('Access-Control-Allow-Headers', 'Authorization, Content-Type, Accept');
			$headers->set('Access-Control-Allow-Credentials', 'true');
			$headers->set('Access-Control-Max-Age', '1728000');
			$headers->set('Cache-Control', 'no-cache, must-revalidate');
		}
	}

	public static function getSubscribedEvents() {
		return [ResponseEvent::class => 'onResponseEvent'];
	}

}
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы