Laravel, ajax, csrf

157
02 мая 2019, 09:30

Возникла проблема с отправкой токена в Laravel. Токен вот здесь:

<meta id="_csrf_token" content="{{ csrf_token() }}">

Форма:

<form id="auth" method="POST" onsubmit="return AuthValidator(this)">
    <input type="text" id="login" name="login" value="">
    <input type="password" id="pass" name="passw" value="">
    <input type="submit" name="logged" value="Login"><br>
</form>

Ajax запрос:

xhttp = new XMLHttpRequest();
//в url - маршрут laravel
        xhttp.open('post', window.location.protocol + '//' + window.location.host + "/auth");
        xhttp.setRequestHeader('X-CSRF-TOKEN', token.content);
        xhttp.send("login="+form.login.value+"&passw="+form.passw.value);
        xhttp.onreadystatechange = function() {
            if(xhttp.readyState == 4 && xhttp.status == 200){
                console.log(xhttp.responseText);
            }
        }

Сам back-end:

if ($request->IsMethod('post')):
    $this->main();
    elseif($request->IsMethod('get')):
        if(View::exists('public.auth')):
            return view('public.auth');
            else: return view('page404');
            endif;
    endif;

Ошибка: TokenMismatchException. Вариант - отключить проверку токена не подходит. Всем благодарен за помощь.

Answer 1

Этот код работает, использовал в своем проекте на Laravel

html:
обрати внимание на атрибут name тега meta

<meta name="csrf-token" content="{{ csrf_token() }}" />

js:

jQuery.ajaxSetup({
   headers: {
     'X-CSRF-TOKEN': $('meta[name = "csrf-token"]').attr('content')
   }
});
jQuery.ajax({
    //ajax запрос
});