Handling CORS Issues in Fetch API

Hello there, guest! Nice to see you here 😊 Join our community to meet our family, chat with us, start a discussion and a lot more!

Register

elvish11

Lurker Lv0️⃣
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:
JavaScript:
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    console.log(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!
 

Sbenny

A crazy scientist
Staff member
Admin
SB Mod Squad ⭐
✔ Approved Releaser
Active User
You could use CURL to save a cached copy of the content of any URLs into a file, so you can then open such file instead of directly accessing the external website.

Example:


PHP:
example.php
<?php

$url = $_GET['url'];

function cache_url($url, $skip_cache = FALSE) {

    // settings

    $cachetime = 604800; //one week

    $where = "gcache";

    if ( ! is_dir($where)) {

        mkdir($where);

    }

    

    $hash = md5($url);

    $file = "$where/$hash.cache";

    

    // check the bloody file.

    $mtime = 0;

    if (file_exists($file)) {

        $mtime = filemtime($file);

    }

    $filetimemod = $mtime + $cachetime;

    

    // if the renewal date is smaller than now, return true; else false (no need for update)

    if ($filetimemod < time() OR $skip_cache) {

        $ch = curl_init($url);

        curl_setopt_array($ch, array(

            CURLOPT_HEADER         => FALSE,

            CURLOPT_RETURNTRANSFER => TRUE,

            CURLOPT_USERAGENT      => 'User-Agent: Mozilla/5.0 (Linux; Android 9; moto g(7) play) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.92 Mobile Safari/537.36',

            CURLOPT_FOLLOWLOCATION => TRUE,

            CURLOPT_MAXREDIRS      => 5,

            CURLOPT_CONNECTTIMEOUT => 15,

            CURLOPT_TIMEOUT        => 30,

        ));

        $data = curl_exec($ch);

        curl_close($ch);

        

        // save the file if there's data

        if ($data AND ! $skip_cache) {

            file_put_contents($file, $data);

        }

    } else {

        $data = file_get_contents($file);

    }

    

    return $data;

}

echo cache_url($url, FALSE);

?>
Then you just type: example.com/example.php?url=the_link_here

and you will be able to access it without any cors issues, also caching it.

Beware you also need to create a folder named "gcache" in the same directory of the example.php file.
 
Top