Invalid request (Unsupported SSL request)

My requests are going through, from postman, but my cannot fetch data from my frontend.
I can’t figure out the error. HELP!!!

Cors middleware

<?php

namespace App\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Routing\RouteContext;

/**
 * CORS middleware.
 */
final class CorsMiddleware implements MiddlewareInterface
{
    /**
     * Invoke middleware.
     *
     * @param ServerRequestInterface $request The request
     * @param RequestHandlerInterface $handler The handler
     *
     * @return ResponseInterface The response
     */
    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): 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('Access-Control-Allow-Origin', '*')
            ->withHeader('Access-Control-Allow-Methods', implode(', ', $methods))
            ->withHeader('Access-Control-Allow-Headers', $requestHeaders ?: '*');

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

        return $response;
    }
}

My bootstrap.php

<?php

declare(strict_types=1);

use App\Application\Middleware\CorsMiddleware;
use App\Application\Settings\SettingsInterface;
use DI\ContainerBuilder;
use Illuminate\Database\Capsule\Manager;
use Slim\Factory\AppFactory;

require __DIR__ . "/../vendor/autoload.php";

$dotenv = \Dotenv\Dotenv::createImmutable(__DIR__ . "/../");
$dotenv->load();

$containerBuilder = new ContainerBuilder();
$settings = require_once __DIR__ . "/settings.php";

$settings($containerBuilder);
$container = $containerBuilder->build();

$settingsInterface = $container->get(SettingsInterface::class);

AppFactory::setContainer($container);

$app = AppFactory::create();

$app->add(CorsMiddleware::class);

$app->addRoutingMiddleware();

$middleware = require_once __DIR__ . "/middleware.php";
$middleware($app);

$routes = require_once __DIR__ . "/routes.php";
$routes($app);


//Elequont
$capsule = new Manager();
$capsule->addConnection($settingsInterface->get('db'));
$capsule->setAsGlobal();
$capsule->bootEloquent();

$app->run();

Routes file

<?php

use App\Application\Action\PreflightAction;
use App\Auth\Actions\AuthLoginAction;
use App\Owera\Clients\Actions\ClientDetailAction;
use App\Owera\Clients\Actions\ClientListAction;
use Slim\App;
use Slim\Interfaces\RouteCollectorProxyInterface as Group;
use App\Owera\Staffs\Actions\StaffListAction;
use App\Owera\Staffs\Actions\StaffDetailAction;
use App\Owera\Staffs\Actions\StaffCreateAction;
use App\Owera\Staffs\Actions\StaffUpdateAction;
use Slim\Exception\HttpNotFoundException;

return function (App $app) {
    // $app->options('/{routes:.+}', function (Request $request, Response $response, $args) {
    //     return $response;
    // });

    $app->group("/api/v1/auth", function (Group $group) {
        $group->post("/login", AuthLoginAction::class);
    });
    $app->options('/api/v1/auth', PreflightAction::class);


    $app->group("/api/v1/staffs", function (Group $group) {
        $group->get("", StaffListAction::class);
        $group->get("/{id}", StaffDetailAction::class);
        $group->put("/{id}", StaffUpdateAction::class);
        $group->post("", StaffCreateAction::class);
    });

    $app->options('/api/v1/staffs', PreflightAction::class);

    $app->group("/api/v1/clients", function (Group $group) {
        $group->get("", ClientListAction::class);
        $group->get("/{id}", ClientDetailAction::class);
    });

    $app->map(['GET', 'POST', 'PUT', 'DELETE', 'PATCH'], '/{routes:.+}', function ($request, $response) {
        throw new HttpNotFoundException($request);
    });
};

Hi @sagarlp

The reason is, Postman doesn’t care about CORS, because it’s a dev tool not a browser.

What kind of error message are you getting?

Get requests are working fine now, but post/put request are not working. This is my error
Access to XMLHttpRequest at 'http://localhost:8080/api/v1/staff/3' from origin 'http://localhost:3000' has been blocked by CORS policy: Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.

I’ve updated my router to :

return function (App $app) {
    $app->options('/{routes:.*}', function (Request $request, Response $response) {
        // CORS Pre-Flight OPTIONS Request Handler
        return $response
            ->withHeader('Access-Control-Allow-Origin', '*')
            ->withAddedHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
            ->withAddedHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
            ->withAddedHeader('Content-Type', 'application/json');
    });

    $app->group("/api/v1/auth", function (Group $group) {
        $group->post("/login", AuthLoginAction::class);
    });

    $app->group("/api/v1/staffs", function (Group $group) {
        $group->get("", StaffListAction::class);
        $group->get("/{id}", StaffDetailAction::class);
        $group->put("/{id}", StaffUpdateAction::class);
        $group->post("", StaffCreateAction::class);
    });

    $app->group("/api/v1/clients", function (Group $group) {
        $group->get("", ClientListAction::class);
        $group->get("/{id}", ClientDetailAction::class);
    });
};

Get requests are working fine now, but post/put request are not working.

This is strange, because the port numbers (3000 → 8080) are different. This might violate Cross Origin rules.

My react app is running in port 3000 and php server in port 8080

It looks like the CORS response headers are just missing.
Try to read this and add the CorsMiddleware as shown in the article.

I’ve added the cors middleware from the article.
One thing I found is,
when i take the route outside of group the post requests go through.

// ...
 $app->put("/api/v1/staffs/{id}", StaffUpdateAction::class); // this works

 $app->group("/api/v1/staffs", function (Group $group) {
        $group->get("", StaffListAction::class);
        $group->get("/{id}", StaffDetailAction::class);
        $group->put("/{id}", StaffUpdateAction::class); // this doesn't work
        $group->post("", StaffCreateAction::class);
    });
//...