L
L
legolas44442015-11-24 22:27:55
CORS
legolas4444, 2015-11-24 22:27:55

How does CORS work in Laravel 5?

Hello! I am developing a public API and a client for it in AngularJS. Faced a problem with CORS.
I made this middelwar:

<?php

namespace App\Http\Middleware;

use Closure;

class CorsMiddleware
{
    /**
     * 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-Origin' , '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, PATCH, HEAD')
            ->header('Access-Control-Allow-Headers', 'Authorization');
    }
}

But I am getting an error:
XMLHttpRequest cannot load http://api.v1.example.local/signup. Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. Origin 'http://german-front.local' is therefore not allowed access.

And if you add to .htaccess
<IfModule mod_headers.c>
   Header set Access-Control-Allow-Origin "*"
   Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS, PATCH, HEAD"
</IfModule>

then everything works. It would seem that it works - let it work. But it is interesting to find out why this is only happening? Who thinks what?
Ps I noticed a strange feature. When OPTIONS is sent, the headers are returned, but the subsequent POST request does not receive the necessary headers..

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
D', 2015-11-24
@Denormalization

See how it is implemented here https://github.com/barryvdh/laravel-cors (specifically here https://github.com/asm89/stack-cors/blob/master/sr... methods isPreflightRequest, handlePreflightRequest) I recommend
this one package with no problems.

O
OnYourLips, 2015-11-24
@OnYourLips

Maybe the rest of the middleware somehow modify it?
I advise you to go through the debugger and find out what's wrong. This method always helps to find the error.
Setting such headers in the desired controller works for me.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question