-2

I have written simple code for angular as frontend and laravel as backend. I have code in my controller like:

PostController.php

public function store(Request $request)
{
   Post::create([
        'post_name'=>$request->post_name,
        'post_text'=>$request->post_text,

    ]);
    return response()->json(['msg'=>'Post Created','success'=>true]);
}

and in my routes.php file, I have:

Route::group([
    'middleware' => ['cors'],
], function ($router) {
     //Add you routes here, for example:
Route::resource('post','API\PostController');  
});

and in angular post.service.ts

addPost(data) {
      const headers = new HttpHeaders({
        'Accept': 'application/json',
        'Content-Type':'application/json'
      });
      let postdata={
        'post_name':data['post_name'],
        'post_text':data['post_text']
      };
      console.log(postdata);
      return this.http.post('http://192.168.1.100/crud/api/post',postdata,{ headers: headers });
  }

and after execution, I am getting an error like:

Failed to load http://192.168.1.100/crud/api/post: 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.

Sand Of Vega
  • 2,297
  • 16
  • 29
Pranav Mandlik
  • 644
  • 6
  • 19
  • 45

2 Answers2

0

This may be due to,

  1. Your request has been rejected by the server. (If is it so then you must enable cross origin in server side )
  2. Your request has some issues.

related to your scenario try, Passing Access-Control-Allow-Origin: * next to content type in your json and check the server configuration.

0

solved this problem by just adding chrome extension Moesif Origin & CORS Changer

Pranav Mandlik
  • 644
  • 6
  • 19
  • 45