Сообщество IT-специалистов
Ответы на любые вопросы об IT
Профессиональное развитие в IT
Удаленная работа для IT-специалистов
protected $middlewareGroups = [ 'web' => [], 'api' => [], 'js' => [ EncryptCookies::class, AddQueuedCookiesToResponse::class, StartSession::class, AuthenticateSession::class, ShareErrorsFromSession::class, AjaxVerifyCsrfToken::class, SubstituteBindings::class, ] ];
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Session\TokenMismatchException; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware; class AjaxVerifyCsrfToken extends Middleware { protected $addHttpCookie = true; protected $except = [ // ]; public function handle($request, Closure $next) { if ( $this->runningUnitTests() || ( $this->isReading($request) && $this->tokensMatch($request) ) ) { return tap($next($request), function ($response) use ($request) { if ($this->shouldAddXsrfTokenCookie()) { $this->addCookieToResponse($request, $response); } }); } throw new TokenMismatchException('Несоответствие CSRF ключа. Перезагрузите страницу.'); } protected function runningUnitTests(): ?bool { return env('APP_ENV') === 'testing'; } protected function isReading($request): ?bool { return in_array($request->method(), ['GET', 'POST', 'HEAD', 'GET', 'OPTIONS']); } }
window.axios = require('axios'); window.axios.defaults.headers.common = { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'), 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/json', };
axios.post('/ajax/post', { id: 9999, }).then(response => { }).catch(function (resp) { console.log(resp); });
$router->group( ['prefix' => '/ajax'], static function (Router $router) { $router->group( ['prefix' => 'post', 'middleware' => ['js'], 'as' => 'js.ajax.post.'], static function (Router $router) { $router ->post('/', PostController@get')->name('get'); ....
<head> ... <meta name="csrf-token" content="{{ csrf_token() }}"> ... </head>