Saurabh Gupta
Saurabh Gupta

Reputation: 122

get request working on api but post is giving error

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');

Upvotes: 1

Views: 937

Answers (2)

Saurabh Gupta
Saurabh Gupta

Reputation: 122

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);
  });
 }

Upvotes: 0

Chandru
Chandru

Reputation: 11192

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;
    });
}

Upvotes: 1

Related Questions