飞行前响应中的Access-Control-Allow-Headers不允许请求标头字段X-CSRF-TOKEN

时间:2018-08-13 10:13:49

标签: laravel cors

我有一个laravel项目,当我运行 php artisan serve 时,浏览器显示错误:

Failed to load http://127.0.0.1:8000/api/news/get-news-list: Request header field X-CSRF-TOKEN is not allowed by Access-Control-Allow-Headers in preflight response.

我的代码如下:

axios.get(domainName+'/api/news/get-news-list').then(response=>{
    news = response.data.list;
}).catch(function (error) {
    console.log(error);
});

我已经添加了如下中间件:

Kernel.php

protected $middleware = [
    \App\Http\Middleware\Cors::class
];

protected $routeMiddleware = [
    'cors' => \App\Http\Middleware\Cors::class
];

Cors.php

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

}

api.php

Route::prefix('news')->group(function () {
    Route::get('get-news-list', 'API\NewsController@getList')->middleware('cors');
});

谁能告诉我如何解决此问题?

1 个答案:

答案 0 :(得分:4)

只需将x-csrf-token标头添加到允许的列表中即可。就您而言,它位于Cors.php文件的标题Access-Control-Allow-Headers中。

Access-Control-Allow-Headers控制在CORS请求中允许使用哪些标头。