В постмане на запрос отдает ответ с нужными заголовками... В браузере на 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.phpclass 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