2
votes

I'm using Angular 5 front-end & Laravel 5.6 Backend as Rest API

Now I'm trying to get Access Token using:

   const url     = 'http://127.0.0.1:8000/oauth/token' ;
   const body    = JSON.stringify({
                      'client_id'    : '8',
                      'client_secret': 'nMfgx0XrlfvImZK1vqu7PucCaaezDZofJOhTLh4m',
                      'grant_type'   : 'password',
                      'username'     : 'admin',
                      'password'     : '0a09943d507c591ae7269042a57db16ac9a2b971'
                    });

    const httpOptions = {
                          headers: new HttpHeaders({
                            'Accept'      : 'application/json',
                            'Content-Type':  'application/json'
                          }
                          )
                        };

    const res  = this.http.post<any>(url, body, httpOptions)
                          .subscribe(myres => { console.log(myres); }) ;

It's working fine on PostMan but With Angular Show this Error:

login:1 Failed to load http://127.0.0.1:8000/oauth/token: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

I heard should use somthing called :

header('Access-Control-Allow-Origin', '*')ce
4
Did you try searching for e.g. "laravel enable CORS"?jonrsharpe
yes i did and i found this header('Access-Control-Allow-Origin', '*')Abdelhadi Abdo

4 Answers

5
votes

you need cors package:

composer require barryvdh/laravel-cors

once installed, go to /config/app.php, add the following to 'providers' array:

Barryvdh\Cors\ServiceProvider::class,

in /app/Http/Kernel.php add the following:

protected $middleware = [
    // ...
    \Barryvdh\Cors\HandleCors::class,
];

afterwards run this:

php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

then add your the url that angular serving from in the allowedOrigins in config/cors.php

    'supportsCredentials' => true,
    'allowedOrigins' => ["localhost:4200"],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['*'],
    'exposedHeaders' => [],
    'maxAge' => 0,

run php artisan config:clear and you are good to go

2
votes
  1. Make new Middleware : php artisan make:middleware addHeadersCors

  2. Put this code inside it (Http/Middleware/addHeadersCors.php):

    public function handle($request, Closure $next)
    {
        return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS')
        ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With');
    }
    
  3. Assign the middleware to the Kernel (Http/Kernel.php) :

    protected $middleware = [
        ..
        ...
        \App\Http\Middleware\addHeadersCors::class,
    ];
    
0
votes

You might or might not need to handle CORS on the server side. You will need CORS if you run your production API backend on a different domain or port than your production front end (which is what I do and would recommend). Then @Hussein's answer is the best one.

But if it's only for local development, where your port differs, I would not add another complexity to your laravel application but would instead solve it with a proxy:

In your angular root directory (where your package.json is), create a file proxy.conf.json

{
    "/api": {
        "target": "http://localhost:8000",
        "secure": false
    }
}

then change your package.json to use this proxy:

"scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.conf.json",
    // other scripts
}

now run the webpack server with npm start instead of ng serve.

See this answer for more details

0
votes

Laravel:

composer require barryvdh/laravel-cors

Edit app/Http/Kernel.php- middlewareGroup 's $middlewareGroups content:

    'api' => [
        \Barryvdh\Cors\HandleCors::class,
        'throttle:60,1',
        'bindings',
    ],