我有一个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');
});
谁能告诉我如何解决此问题?
答案 0 :(得分:4)
只需将x-csrf-token
标头添加到允许的列表中即可。就您而言,它位于Cors.php
文件的标题Access-Control-Allow-Headers
中。
Access-Control-Allow-Headers
控制在CORS请求中允许使用哪些标头。