Reputation: 23
When I make a post request, server gives to me the following error: 'XMLHttpRequest cannot load http://localhost/pets2homeback/public/register. Request header field X-XSRF-TOKEN is not allowed by Access-Control-Allow-Headers in preflight response.' I followed your post and I'm not able to allow this X-XSRF-TOKEN in Access-Control-Allow-Headers and I don't really understand the problem because the route is a register, so there is no token, and I don't really know where the problem is.
This is my kernel.php (the important point)
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\Cors::class,
\App\Http\Middleware\VerifyCsrfToken::class];
This is my cors.php
/**
* 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-Headers', '*')
->header('Allow', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
and this is my routes.php (in Laravel 5.3 is web.php)
header('Access-Control-Allow-Origin','http://localhost');
header('Access-Control-Allow-Credentials', 'true');
Route::get('/', 'IndexController@getIndex');
Route::post('/login', [ 'uses' => 'LoginController@loginAction']);
Route::post('/register', [ 'uses' => 'UserController@register']);
And this is my service in Angular2.
register(input){
let params = JSON.stringify(input);
let headers = new Headers({'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'});
return this._http.post(this.url+"register", params,{headers: headers})
.map(res => res.json())
}
Upvotes: 1
Views: 5299
Reputation: 4671
I was running into the same issue. Not with Laravel, but with a PHP background.
What solved the problem for me was to define the headers like this:
header('Access-Control-Allow-Headers: Content-Type, x-xsrf-token, x_csrftoken');
Angular is using only XSRF-Token
, but somehow I had to define both.
Hope it helps.
Upvotes: 4