Handling CORS Issues in Fetch API

You can make use of middlewares to handle CORS headers. Here’s a simple example to set CORS headers:

First, handle all “OPTIONS” (pre-flight) requests with an empty response, but let all other request pass through:

if ($request->getMethod() === 'OPTIONS') {
    $response = new Response();
} else {
    $response = $handler->handle($request);
}

Then add the special CORS response headers to allow the request:

$response = $response
    ->withHeader('Access-Control-Allow-Credentials', 'true')
    ->withHeader('Access-Control-Allow-Origin', '*')
    ->withHeader('Access-Control-Allow-Headers', '*')
    ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS')
    ->withHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
    ->withHeader('Pragma', 'no-cache');

Optional handle warnings and notices, so they won’t affect your CORS headers.

if (ob_get_contents()) {
    ob_clean();
}

Then return the response:

return $response;

Add this middleware after the Slim error handler middleware.

For example:

$app->addErrorMiddleware(true, true, true);
$app->add(\App\Middleware\CorsMiddleware::class);
2 Likes