0
votes

Using:

Back: Laravel/Passport Front: ReactJs/Axios

I want to get data in my page, and if I run:

axios.get('http://localhost:8000/api/posts')
  .then(response => {
    console.log(response.data);
  })
  .catch((error) => {
    console.log('error ' + error);
  });

GET http://localhost:8000/api/posts net::ERR_ABORTED 401 (Unauthorized)

Access to XMLHttpRequest at 'http://localhost:8000/api/posts' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

And if I add:

 headers: {
  Authorization: 'Bearer ' + token,
  crossDomain: true,
  'Access-Control-Allow-Origin': '*'
}

Access to XMLHttpRequest at 'http://localhost:8000/api/posts' from origin 'http://localhost:3000' 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.

In laravel/ api.php:

Route::middleware('auth:api')->group(function () {
    Route::get('posts', 'PostController@index');
});

AuthServiceProvider.php

    $this->registerPolicies();
    Route::group([ 'middleware' => [ \App\Http\Middleware\CORS::class ]], function() {
        Passport::routes();
    });

RouteServiceProvider.php

$this->mapApiRoutes();

$this->mapWebRoutes();

Route::group([
    'middleware' => ['auth:api', 'cors'],
    'namespace' => $this->namespace,
    'prefix' => 'auth:api',
], function ($router) {
    Route::apiResource('posts','PostController');
});

But if I remove headers from axios and also move route outside of passport auth, it work fine, I mean like this outside of group:

Route::get('posts', array('middleware' => 'cors', 'uses' => 'PostController@index'));

So, how can I get data from Laravel API with passport auth with axios in reactjs?

UPDATE:

Route::group(['prefix' => 'auth:api', 'middleware' => 'cors'], function(){

    Route::get('posts', 'PostController@index');
});

404 (Not Found)

I used cors on group too, but still the same and 404 error.

1
you are missing the cors middleware on the group. - Davin Tryon
@DavinTryon I added cors to group on RouteServiceProvider.php and also AuthServiceProvider.php nothing different - tour travel
In your middleware try putting cors as first one.. - Panther
@Panther See my answer updated - tour travel
use something like Route::group([ 'middleware' => ['cors', 'auth:api'],... - Panther

1 Answers

0
votes

For allowing CORS we must enable request on both side as server side and also on client side Might be it help add in request header section in axios

headers: {"Access-Control-Allow-Origin": "*"}

and for routes add

Route::options(
    '/{any:.*}', 
    [
        'middleware' => ['CorsMiddleware'], 
        function (){ 
            return response(['status' => 'success']); 
        }
    ]
);

and CorsMiddleware.php will be like as

<?php 

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;

class CorsMiddleware
{
    protected $settings = array(
        'origin' => '*',    // Wide Open!
        'allowMethods' => 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
    );

    protected function setOrigin($req, $rsp) {
        $origin = $this->settings['origin'];
        if (is_callable($origin)) {
            // Call origin callback with request origin
            $origin = call_user_func($origin,
                        $req->header("Origin")
                    );
        }
        $rsp->header('Access-Control-Allow-Origin', $origin);
    }

    protected function setExposeHeaders($req, $rsp) {
        if (isset($this->settings['exposeHeaders'])) {
            $exposeHeaders = $this->settings['exposeHeaders'];
            if (is_array($exposeHeaders)) {
                $exposeHeaders = implode(", ", $exposeHeaders);
            }

            $rsp->header('Access-Control-Expose-Headers', $exposeHeaders);
        }
    }

protected function setMaxAge($req, $rsp) {
    if (isset($this->settings['maxAge'])) {
        $rsp->header('Access-Control-Max-Age', $this->settings['maxAge']);
    }
}

protected function setAllowCredentials($req, $rsp) {
    if (isset($this->settings['allowCredentials']) && $this->settings['allowCredentials'] === True) {
        $rsp->header('Access-Control-Allow-Credentials', 'true');
    }
}

protected function setAllowMethods($req, $rsp) {
    if (isset($this->settings['allowMethods'])) {
        $allowMethods = $this->settings['allowMethods'];
        if (is_array($allowMethods)) {
            $allowMethods = implode(", ", $allowMethods);
        }

        $rsp->header('Access-Control-Allow-Methods', $allowMethods);
    }
}

protected function setAllowHeaders($req, $rsp) {
    if (isset($this->settings['allowHeaders'])) {
        $allowHeaders = $this->settings['allowHeaders'];
        if (is_array($allowHeaders)) {
            $allowHeaders = implode(", ", $allowHeaders);
        }
    }
    else {  // Otherwise, use request headers
        $allowHeaders = $req->header("Access-Control-Request-Headers");
    }
    if (isset($allowHeaders)) {
        $rsp->header('Access-Control-Allow-Headers', $allowHeaders);
    }
}

protected function setCorsHeaders($req, $rsp) {
    // http://www.html5rocks.com/static/images/cors_server_flowchart.png
    // Pre-flight
    if ($req->isMethod('OPTIONS')) {
        $this->setOrigin($req, $rsp);
        $this->setMaxAge($req, $rsp);
        $this->setAllowCredentials($req, $rsp);
        $this->setAllowMethods($req, $rsp);
        $this->setAllowHeaders($req, $rsp);
    }
    else {
        $this->setOrigin($req, $rsp);
        $this->setExposeHeaders($req, $rsp);
        $this->setAllowCredentials($req, $rsp);
    }
}
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
    public function handle($request, Closure $next) {
        if ($request->isMethod('OPTIONS')) {
            $response = new Response("", 200);
        }
        else {
            $response = $next($request);
        }
        $this->setCorsHeaders($request, $response);
        return $response;
    }
}

and make sure used it to working CorsMiddleware

$app->routeMiddleware([
    'CorsMiddleware' => App\Http\Middleware\CorsMiddleware::class,
]);