Wai Yan Hein
Wai Yan Hein

Reputation: 14771

Unable to make HttpClient post request in Angular because of CORS issue

I am developing a Web application using Angular. Backend API is developed using Laravel PHP framework. I enabled the CORS access creating a middleware in the Laravel.

This is the Laravel middleware

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
        ->header('Access-Control-Allow-Headers','X-Requested-With,content-type')
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }
}

I can successfully make the GET request like this.

this.http.get<IEvent[]>(this.globals.API_ENDPOINT + "event/list?email=" + email).subscribe(data=> {
    //do something with the data
});

The above GET request is working fine. But the problem is with making POST request with some parameters.

I send the POST request like this.

var formData = {
   name: "My name"
}
this.http.post<ISimpleForm>(this.globals.API_ENDPOINT + "event/post", formData).subscribe(data=>{

})

As you can see the formData variable is object. When I send the request, I got this error in console.

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 

I tried lots of solution online. For example, passing headers with "Content-Type" with "application/json" and so on. None of them helped. I already solved CORS issue in the server side as well.

But the request is working when I send the body it as string like this

this.http.post<ISimpleForm>(this.globals.API_ENDPOINT + "event/post", formData).subscribe(data=>{

    })

The CORS error is gone when I stringify the body. But the problem is when I log the request data in the server side using $_POST, nothing is passed to the request. So the body is empty.

So, how can I make post request with some request parameters using HttpClient in Angular? What is wrong with my code and how can I fix it?

Upvotes: 0

Views: 1335

Answers (1)

vishal pardeshi
vishal pardeshi

Reputation: 334

I got the same error a while ago. this middleware works for methods not for preflight header. Check this Laravel 5.2 CORS, GET not working with preflight OPTIONS

Suggesting this to use in your project github.com/barryvdh/laravel-cors instead of middleware.

Upvotes: 1

Related Questions