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
{
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