laravel 预检响应中的 Access-Control-Allow-Headers 不允许请求头字段 X-CSRF-TOKEN

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51819968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:58:16  来源:igfitidea点击:

Request header field X-CSRF-TOKEN is not allowed by Access-Control-Allow-Headers in preflight response

laravelcors

提问by jimmy

I had a laravel project, when I run php artisan serve, there shows an error in browser:

我有一个 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.

my code is like following:

我的代码如下:

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

And I already add middleware like following:

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

Kernel.php

内核.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

api.php

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

Can anyone tell me how to fix this problem?

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

回答by Giedrius Kir?ys

Just add x-csrf-tokenheader to allowed list. In your case, it's in Cors.phpfile, header Access-Control-Allow-Headers.

只需将x-csrf-token标题添加到允许列表。在您的情况下,它位于Cors.phpfile, header 中Access-Control-Allow-Headers

Access-Control-Allow-Headerscontrols what headers are allowed in CORS request.

Access-Control-Allow-Headers控制 CORS 请求中允许的标头。