Handling CORS Issues in Fetch API

I’m working on a web development project where I’m using the Fetch API to make cross-origin requests to a different domain. However, I’m running into CORS (Cross-Origin Resource Sharing) issues, and my requests are being blocked. I’ve tried a few solutions I found online, but I’m still having trouble. Here’s a simplified version of my code:

  .then(response => response.json())
  .then(data => {
  .catch(error => {
    console.error('Error fetching data:', error);

I’ve heard about using CORS headers on the server-side to allow cross-origin requests, but I’m not sure how to implement them. Can someone guide me on the proper way to handle CORS issues? How do I configure my server to allow requests from my domain? I’m using Express.js on the server side. Any help would be greatly appreciated!

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()) {

Then return the response:

return $response;

Add this middleware after the Slim error handler middleware.

For example:

$app->addErrorMiddleware(true, true, true);