1

I am trying to call Laravel API in angular:

search(data){ console.log(data); this.http.get('http://localhost:8000/flight',JSON.stringify(data)) .subscribe(res=>{ console.log(res); }); } 

the above is working with GET request.

 search(data){ console.log(data); this.http.post('http://localhost:8000/flight',JSON.stringify(data)) .subscribe(res=>{ console.log(res); }); } 

but not working with POST request

this is the error i get :

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

even though i have my cors middelware written correctly

 return $next($request)->header('Access-Control-Allow-Origin', '*') ->header('Access-Control-Allow-Credentials', true ) ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS') ->header('Access-Control-Allow-Headers',' Origin, Content-Type, X-Auth-Token'); 
5
  • It is CORS issue on the server Commented Sep 20, 2017 at 6:42
  • can you please just explain me sir iam new to laravel and angular Commented Sep 20, 2017 at 6:43
  • 1
    No sir , i dnt know any sir you need to enable CORS in lavel api github.com/barryvdh/laravel-cors Commented Sep 20, 2017 at 6:44
  • but i have enabled it by writing the cors middleware and i have also added it in my RouteServiceProvider Commented Sep 20, 2017 at 6:46
  • The only way to know if you really wrote it correctly is to look at the network tab in your developer tools and see if your local server actually returns the CORS header. Commented Sep 20, 2017 at 6:51

2 Answers 2

1

Try like this in your post method:

in laravel server side :

Header set Access-Control-Allow-Origin "http://localhost:3000" (or) header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization, If-Modified-Since, Cache-Control, Pragma"); 

Restarting apache is neccessary.

post Method in angular

search(data: any) { return this.http.post('http://localhost:8000/flight', data).map(res => { const jsonResponse = res.json(); return jsonResponse; }); } 
Sign up to request clarification or add additional context in comments.

Comments

0

I just had to make a change in the code i.e (Remove JSON.stringify) because it was sending string instead of json object

 search(data){ console.log(data); this.http.post('http://localhost:8000/flight',data) .subscribe(res=>{ console.log(res); }); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.