dongnai6973 2016-12-30 04:18
浏览 54

标题Laravel 5.3 + Angular2中不允许使用X-XSRF-TOKEN

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())

}

  • 写回答

1条回答 默认 最新

  • doutangguali32556 2017-06-17 15:09
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大