Welcome Guest, Not a member yet? Register   Sign In
CORS Error when sending request to my REST API
#1

Hi guys, I am in the process of finalising my app but struggling to understand CORS policies on the server side. Or maybe i am just implementing it wrong. 

I have an RestAPI developed using Codeigniter and JSON web tokens. When i test it using postman it works fine. The cors issue happens only when i have added the controller name inside the filter aliases that should run before to check if access token is valid. 

Any help would do. Here is my code as implemented in CI4 and Ionic 7

PHP Code:
public function getHomeAddress()
    {
        
        header
'Access-Control-Allow-Origin: *' );
        

        
if ( $_SERVER'REQUEST_METHOD' ] == "OPTIONS" )
        {
            
            header
'Access-Control-Allow-Credentials: true' );
            header'Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS' );
            header'Access-Control-Allow-Headers: ACCEPT, ORIGIN, X-REQUESTED-WITH, CONTENT-TYPE, AUTHORIZATION' );
            header'Access-Control-Max-Age: 86400' );
            header'Content-Length: 0' );
            header'Content-Type: application/json; charset=utf-8' );
            die ;
        }

        $user_id $this->request->getVar('user_id');
        
        
        
try {

            $model = new AddressModel();
            $user $model->where('user_id'$user_id)->first();

            return $this->getResponse(
                [
                    'message' => 'success',
                    'user' => $user
                
]
            );

        } catch (Exception $e) {
            
            
return $this->getResponse(
                [
                    'message' => 'Could not find address for specified ID'
                ],
                ResponseInterface::HTTP_NOT_FOUND
            
);
        }
    


Code:
async getAddressDetails(){
    const {value} = await Preferences.get({ key: 'user'});
    const user = JSON.parse(`${value}`);

    const options = {
      url: 'https://usersauth.example.com/UserAddress/gethomeaddress?user_id=' + user.user_id,
      headers: { 'Authorization': `Bearer ${user.token}` }
    };

    const response: HttpResponse = await CapacitorHttp.get(options);


  if(response['status'] == 400){
    var data = response['data'];
    var output='';
    var errorhead = "Ooops";
    for(var key in data) {
        output+= data[key] + '<br>';

    }
    this.showAlert('Ooops',output); 
  }
    if(response['status'] == 200){
      this.currentaddress = response['data']['user']['homeaddress'];
       
        this.homelat = response['data']['user']['homelat'];
        this.homelng = response['data']['user']['homelng'];
    }

  }

So if the controller userAddress is not added in the filters it works but that means there is no security access control in place. So far i have been only testing with userAddress. I want to add all my controllers once this works. Problems starts when i add controller to filters. Everything else works as it should. If you have a better way for me to implement this please help me out. Thanks in advance 

PHP Code:
public $filters = [
 
'auth' => [
 
  'before' => [
 
'UserAddress/*'
 
],
 ]
 ]; 
Reply
#2

You need to accept OPTIONS requrest.
See https://developer.mozilla.org/en-US/docs...d_requests
Reply




Theme © iAndrew 2016 - Forum software by © MyBB