mercredi 15 février 2017

Laravel 5.2 - OPTIONS Request Type Not Being Detected by getMethod() in Middleware

I am using the following middleware to allow CORS access to my Laravel back-end:

public function handle($request, Closure $next)
{
    header('Access-Control-Allow-Origin: *');

    // ALLOW OPTIONS METHOD
    $headers = [
        'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
        'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization'
    ];
    if ($request->getMethod() == "OPTIONS") {
        // The client-side application can set only headers allowed in Access-Control-Allow-Headers
        return Response::make('OK', 200, $headers);
    }

    $response = $next($request);
    foreach ($headers as $key => $value)
        $response->header($key, $value);
    return $response;
}

The above works well as long as I am not sending a preflight OPTIONS request. When I send an OPTIONS request, $request->getMethod() should detect that it's an OPTIONS request and return a 200 with the appropriate headers. I noticed that $request->getMethod() returns an empty string any time I make an OPTIONS request, but it returns the correct request type if it's any other type of request (GET, POST, PUT, DELETE).

As a result of this, my OPTIONS requests are never caught and the code inside of the conditional if statement is not executed.

Why is $request->getMethod() returning an empty string when I am sending OPTIONS requests to the server?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2lj0xA1
via IFTTT

Aucun commentaire:

Enregistrer un commentaire