jeudi 16 mai 2019

CORS request error (react native / laravel passport)

I created a mobile app which consumes a back-end API.I am using fetch api on JS end to make my requests. However, I am getting a CORS error

Error message: Access to fetch at 'mydomain.com' from origin 'null' 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.

I have tried the following:

A/ In my .htaccess

 RewriteEngine On
 RewriteCond %{HTTPS} off
 RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]]
 <FilesMatch ".(ttf|otf|eot|woff)$">
 <IfModule mod_headers.c>
 Header set Access-Control-Allow-Origin "*"
 Header set Access-Control-Allow-Methods "GET,POST,OPTIONS,DELETE,PUT"
 Header set Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With, token"
 Header set Access-Control-Allow-Credentials "true"
 </IfModule>

This had the effect of at least letting my GET request to pass.

B/ in my index.php

header("Access-Control-Allow-Origin: *")
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 1000");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE");

Same effect as .htaccess, only GET request passes, with OPTIONS . I also saw the my Access-Control-Allow-Origin would be "*, null" and i would get an error stating that only one is allowed.

C. https://github.com/barryvdh/laravel-cors In AuthServiceProvider, i tried both these. Only one at a time, not at the same time.

        Route::group([ 'middleware' => 'cors'], function() {
            Passport::routes();
        });

    Passport::routes(null, ['middleware' => [ \Barryvdh\Cors\HandleCors::class ]]);

D. Created a custom middle with this code

    public function handle($request, Closure $next)
    {
                return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }


I dumped my $_SERVER and could not find the HTTP_ORIGIN, HTTP_REFERER. I did get my HTTP_REMOTE_ADDR

What is even more frustrating was that my app was working correctly, and I just suddenly started having the issue (back-end hosted on bluehost)



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire