Laravel Angular CORS authentication problem

I follow this guide to set up authentication with tokens using Laravel and Angular.

https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps

This works fine, but when I host Laravel (as a backend) separately and Angular frontend in a different domain, I get an error when starting in the console: -

XMLHttpRequest cannot load http://jotdot.mysite.com/api/authenticate.
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://jotdotfrontend.mysite.com' is 
therefore not allowed access.

I hosted the CORS middleware in Laravel and works great for simple routes.

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-Origin', '*')-  >header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}

}

How to add CORS middleware to this: -

Route::group(['prefix' => 'api', 'middleware' => 'cors'], function()
{
    Route::resource('authenticate', 'AuthenticateController', ['only' =>    ['index']]);
    Route::post('authenticate', 'AuthenticateController@authenticate');
});

Adding it next to ['prefix' => 'api'] did not solve the problem.

thanks

+4
source share
2 answers

, , , , "", . , .

handle :

public function handle($request, Closure $next)
{
    $request->header('Access-Control-Allow-Origin', '*');
    $request->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    $request->header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');

    return $next($request);
}
+2
0

Source: https://habr.com/ru/post/1614411/


All Articles