2

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
2
  • Did you try searching for e.g. "laravel enable CORS"? Commented Apr 9, 2018 at 20:22
  • yes i did and i found this header('Access-Control-Allow-Origin', '*') Commented Apr 9, 2018 at 20:54

4 Answers 4

5

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

Sign up to request clarification or add additional context in comments.

Comments

2
  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,
    ];
    

1 Comment

Assuming you found this somewhere, please reference it correctly by providing a link to the source. Otherwise it's plagiarism.
0

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

Comments

0

Laravel:

composer require barryvdh/laravel-cors

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.