JS fetch + php codeigniter4 CORS issue - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Friday, September 23, 2022

JS fetch + php codeigniter4 CORS issue

I'm using vue3 with codeigniter4 .I am getting a CORS issue with fetch When sending a custom header even I set what should be set for CORS in server side method (Without using the framework filters ,Just pure php)

my js code is :

GetMyOrders() {
            fetch(this.AppMainData.ApiUrl+'orders/get', {
                   method: 'GET',
                   headers:{
                    'Role': 'some role',
                    }
                }).then(response => response.json())
                .then(data => {
                    console.log(data);
                    this.MyOrders = data.result;
                    this.explode;
                    return;

                })
        }

And my php code in codeigniter controller (Not resource) is :

public function GetMyOrders(){
            header('Access-Control-Allow-Origin: *');
            header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
            header('Access-Control-Allow-Headers: Role ,Content-Type,Origin');
            header('Access-Control-Allow-Credentials:true');
            $db=\Config\Database::connect();
            $data['result']=$db->query("Some SQL Query")->getResult();
         return json_encode($data);
        }

The fetch is successful when not fetching with header , but when i add my custom header the response is blocked by CORS policy as bellow:

"Access to fetch at 'http://localhost/MyApp/public/api/orders/get' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."

Any idea please (Without using External Solutions) !!!



source https://stackoverflow.com/questions/73819282/js-fetch-php-codeigniter4-cors-issue

No comments:

Post a Comment