Igor Simic
5 years ago

Header value not available in angular interceptor


CORS stands for Cross-Origin Resource Sharing an is a specification that allow modern browsers to request (and receive) data from a domain other than the one serving the page that made the request. If this is the first time you’re hearing about this, please allow me to introduce you to these two great resources: -http://www.html5rocks.com/en/tutorials/cors/ -http://enable-cors.org So you’re building your API using Laravel and when when you try to make a XHR request you see the following message in your browser’s console: This means your server is not sending back to the client the headers that allow CORS: 1.Access-Control-Allow-Origin 2.Access-Control-Allow-Methods So how to implement this in Laravel? Super easy! Middlewares come to the rescue. Using your Terminal, navigate to your project’s root directory and issue the following artisan command:


php artisan make:middleware Cors


Now, using your editor of choice, change the newly created /app/Http/Middleware/Cors.php so it look like this:





namespace App\Http\Middleware;

use Closure;

class Cors {
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-Type, Accept, Token, RefreshedToken')
            ->header('Access-Control-Expose-Headers', 'RefreshedToken');
    }
}


Next update /app/Http/Kernel.php adding the following instruction which will make Laravel aware of your custom middleware:





protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'cors' => \App\Http\Middleware\Cors::class, // <<< add this line
];


To wrap things up, just use your middleware as you’re used to:





Route::get('breweries', ['middleware' => 'cors', function()
{
    return \Response::json(\App\Brewery::with('beers', 'geocode')->paginate(10), 200);
}]);