Answer the question
In order to leave comments, you need to log in
Why can't I return the Access-Control-Allow-Origin (CORS) header to the browser?
In the postman, it gives a response to the request with the necessary headers ... In the browser, GET also responds to OPTIONS, and to POST it says that there is no header.
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('Запрос отправляется');
});
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;
}
}
Answer the question
In order to leave comments, you need to log in
js error. That's right:
data: JSON.stringify({
"login": $('#slick-register input[name="login"]').val(),
"password": $('#slick-register input[name="password"]').val()
}),
take away
->withHeader('Access-Control-Allow-Headers', '...')
->withHeader('Access-Control-Allow-Methods', '...');
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question