@GoodForest

Почему не удается вернуть в браузер заголовок Access-Control-Allow-Origin (CORS)?

В постмане на запрос отдает ответ с нужными заголовками... В браузере на OPTIONS отвечает и GET, а на POST - регается, что заголовка нет.

Access to XMLHttpRequest at '' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

$app->addBodyParsingMiddleware();
$app->add(\app\middleware\CorsMiddleware::class);
$app->addRoutingMiddleware();
$app->options('/{routes:.+}', function ($request, $response, $args) {
    return $response
        ->withStatus(200)
        ->withHeader('Access-Control-Allow-Origin', '*')
        ->withHeader('Access-Control-Allow-Headers', '*'));
});
$app->post('/register',
    'app\controllers\DefaultController:createUser');

$("#btnreg").click(function(){
		var formData = JSON.stringify($("#slick-register").serializeArray());
		$.ajax({
		  type: "POST",
		  url: 'http://host:port/register',
		  data: {
			"login": $('#slick-register input[name="login"]').val(),
			"password": $('#slick-register input[name="password"]').val()

		  },
		  success: function(){alert('ok');},
		  dataType: "json",
		  contentType : "application/json"
		});
			
    console.log('Запрос отправляется');
});

Мой класс:
CorsMiddleware.php
class CorsMiddleware implements MiddlewareInterface
{

    public function process(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Server\RequestHandlerInterface $handler): \Psr\Http\Message\ResponseInterface
    {
        $routeContext = RouteContext::fromRequest($request);
        $routingResults = $routeContext->getRoutingResults();
        $methods = $routingResults->getAllowedMethods();
        $requestHeaders = $request->getHeaderLine('Access-Control-Request-Headers');

        $response = $handler->handle($request);

        $response = $response
            ->withHeader('Origin', ['*'])
            ->withHeader('Access-Control-Allow-Origin', ['*'])
            ->withHeader('Access-Control-Request-Method', ['*'])
            ->withHeader('Access-Control-Request-Headers', ['*'])
            ->withHeader('Access-Control-Allow-Headers', ['Content-Type'])
            ->withHeader('Access-Control-Expose-Headers', ['*'])
            ->withHeader('Access-Control-Allow-Methods', ['POST, PUT, OPTIONS, GET, DELETE']);

        // Optional: Allow Ajax CORS requests with Authorization header
//        $response = $response->withHeader('Access-Control-Allow-Credentials', 'true');

        return $response;
    }
}

Использую этот фреймворк с гита - Comet: gotzmann/comet
  • Вопрос задан
  • 321 просмотр
Решения вопроса 1
@GoodForest Автор вопроса
Ошибка в js. Так правильно:
data: JSON.stringify({
			"login": $('#slick-register input[name="login"]').val(),
			"password": $('#slick-register input[name="password"]').val()
		  }),
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
SilenceOfWinter
@SilenceOfWinter Куратор тега PHP
та еще зажигалка...
убери
->withHeader('Access-Control-Allow-Headers', '...')
        ->withHeader('Access-Control-Allow-Methods', '...');


из ошибки ясно что твой response класс - говно т.к. преобразует заголовки
Ответ написан
Ваш ответ на вопрос

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

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