Monday, November 30, 2020
therichposts@gmail.com
Angular 8Angular 9Laravel 6Rest Api

Solved Laravel Angular cors issue

Angular 9 Laravel 7 Auth Login working tutorial Part 2

Hello to all, welcome to therichpost.com. In this post, I will tell you, Solved Laravel Angular cors issue.

Solved Laravel Angular cors issue
Solved Laravel Angular cors issue

Post Working:

In this post, I will make laravel cors middleware, which will remove the cors issue during Angular laravel API call to get the data in Angular Application from laravel. I am doing this in Laravel 6 and Angular 8.

Here is the complete working steps and please follow carefully:

1. Here is the below php artisan command you need to run into your terminal to create Cors middleware into your Laravel Application:

php artisan make:middleware Cors

2. After run above command,  you will see app\Http\Middleware\Cors.php file with below code into your middleware folder:

<?php
namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */

    public function handle($request, Closure $next)
    {
        // ## This is custom code for remove cors issue ##
        return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }
}

3. Now you have to run below code into your app\Http\kernel.php file:

protected $routeMiddleware = [
    ...
   'cors' => \App\Http\Middleware\Cors::class,
];

4. Here is the code you need to routes/api.php file:

Route::get('/get-data','HomeController@getdata')->middleware("cors");

Here come to Angular component code in which I make API call to get data from laravel

1. Here is the code, which I wrote into my app.component.ts file:

...
import { HttpClient} from '@angular/common/http';
...
export class HomeComponent implements OnInit {
  data: any;
  constructor(private http: HttpClient) {
    
    this.http.get('http://locahost/Laravel/PROJECTNAME/public/api/get-data').subscribe(data => {
        this.data = data;
        console.log("Data is coming.");
       
        }, error => console.error(error));
   }
}

This is it. If you have any kind of query related to this post then do comment below.

The main purpose of this post is to solve cors issue into Angular Laravel API calls.

Jassa

Thank you

Ajay Malhotra
the authorAjay Malhotra
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know Wordpress, Core php, Angularjs, Angular 2, Angular 6, Angular 7, Angular 8, Angular 9, Angular 10, Angular 11, Nodejs, laravel, Codeigniter, Shopify, Squarespace, Jquery, Google Map Api, Vuejs, Reactjs, Bigcommerce etc.

2 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.