G
G
GoodForest2021-05-12 18:46:03
PHP
GoodForest, 2021-05-12 18:46:03

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('Запрос отправляется');
});

My class:
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;
    }
}

I use this framework from git - Comet: gotzmann/comet

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GoodForest, 2021-05-13
@GoodForest

js error. That's right:

data: JSON.stringify({
      "login": $('#slick-register input[name="login"]').val(),
      "password": $('#slick-register input[name="password"]').val()
      }),

A
Anton Shamanov, 2021-05-12
@SilenceOfWinter

take away

->withHeader('Access-Control-Allow-Headers', '...')
        ->withHeader('Access-Control-Allow-Methods', '...');

it is clear from the error that your response class is shit. converts headers

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question