Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

cors

laravel

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

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

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');
});

Can anyone tell me how to fix this problem?

like image 805
jimmy Avatar asked Aug 13 '18 10:08

jimmy


People also ask

What is X CSRF token?

A CSRF token is a unique, secret, unpredictable value that is generated by the server-side application and transmitted to the client in such a way that it is included in a subsequent HTTP request made by the client.

What is Access Control expose headers?

The Access-Control-Expose-Headers response header allows a server to indicate which response headers should be made available to scripts running in the browser, in response to a cross-origin request. Only the CORS-safelisted response headers are exposed by default.

What is X requested with header?

X-Requested-With is not a standardized header, but it is commonly used as a flag to mark AJAX (Asynchronous JavaScript and XML) requests. In that sense, WebView's use of the field for a different purpose can cause issues for some web pages.


1 Answers

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

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

like image 144
Giedrius Kiršys Avatar answered Oct 02 '22 13:10

Giedrius Kiršys