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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With