简体   繁体   English

Ajax定期工作。 有时POST请求返回错误419

[英]Ajax works periodically. Sometimes POST request return error 419

With the help of Laravel I create a multilingual website. 在Laravel的帮助下,我创建了一个多语言网站。 When I switch languages using Ajax, sometimes I get an error. 当我使用Ajax切换语言时,有时会出错。 Javascript code: Javascript代码:

$(document).ready(function(){
    $("#LanguageSwitcher").change(function(){
        var locale = $(this).val();
        var _token = $('meta[name="csrf-token"]').attr('content');

        $.ajax({
            url: "/language",
            type: 'POST',
            data: {locale: locale, _token: _token},
            datatype: 'json',
            beforeSend: function () {
                console.log('before send - ' + locale);
            },
            success: function (data) {
                console.log('success');
            },
            error: function (error) {
                console.log(error);
            },
            complete: function (data) {
                    window.location.reload(true);
            }
        });
    });
});

web.php: web.php:

Route::post('/language/', array(
    'before' => 'csrf', 
    'uses' => 'LanguageController@changeLanguage' 
));

Controller: 控制器:

class LanguageController extends Controller
{
    public function changeLanguage(Request $request){
        if ($request->ajax()) {
            $request->session()->put('locale', $request->locale);
        }
    }
}

layout.blade.php: layout.blade.php:

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

        <select id="LanguageSwitcher" class="btn btn-outline-danger">
                <option>...code...</option>
                <option>...code...</option>
                <option>...code...</option>
        </select>

When I go through another browser everything works. 当我浏览另一个浏览器时,一切正常。 It also works if I go through the incognito mode. 如果我通过隐身模式,它也有效。 Can this be due to the fact that I log in to the admin panel? 这可能是因为我登录管理面板了吗?

Put your ajax call like this. 像这样把你的ajax调用。

req = $.ajax({
    type: "POST",
    url: "/search",
    data: {
        "locale": locale,
        "_token": "{{ csrf_token() }}",
    },
    dataType: "json",
    success: function(msg){

    }
});

As I saw your code. 正如我看到你的代码。 You passing csrf token in your request. 您在请求中传递csrf令牌。 the problem you face is, your csrf token is not being updated. 您遇到的问题是,您的csrf令牌未被更新。

Let's say, you're not reloading your page, on first time your enter to your page, laravel give you csrf token which you providing to ajax through meta . 比方说,当你第一次进入你的页面时,你没有重新加载你的页面,laravel给你csrf令牌,你通过meta提供给ajax。

But after some time on the backend(laravel side). 但是经过一段时间后(laravel方面)。 your csrf token is updated, but you don't have updated one in client-side.For get the updating one you need to reload the page. 您的csrf令牌已更新,但您在客户端没有更新的令牌。要获得更新,您需要重新加载页面。

so for this issue, you need to check whenever you get error status 419, request laravel for new csrf token(by making a new route get the csrf token from laravel helper csrf_token() return back to ajax) and update to your file. 所以对于这个问题,你需要检查每当你得到错误状态419,请求新的csrf令牌laravel(通过使新的路由从laravel helper获取csrf令牌csrf_token()返回到ajax)并更新到你的文件。 and send back that token to laravel with you request. 并根据您的请求将该令牌发回给laravel。

For updating newly token to your page 用于将新令牌更新到您的页面

document.querySelector('meta[name=csrf-token]').setAttribute('content', res.data.csrf);

or you can refresh your token by reloading the page 或者您可以通过重新加载页面来刷新令牌

add csrf token in meta tag in your blade view 在刀片视图中的元标记中添加csrf标记

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

in your ajax function : 在你的ajax函数中:

  $.ajax({
            url: '/search',
            headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
            type: 'POST',
            dataType: 'json',
            success: function(response) {

            },error:function(err){

            }
    });

I found the answer, but still did not understand how it works, explain who understands this. 我找到了答案,但仍然不明白它是如何工作的,解释谁理解这一点。 App\\Exceptions\\Handler.php 应用程序\\例外\\ Handler.php

public function render($request, Exception $exception)
    {
        // code for updating token when session is expired
        if ($exception instanceof \Illuminate\Session\TokenMismatchException) {            
            return Redirect::back()->withErrors(['session' => 'Sorry, your session seems to have expired. Try Again']);
        }

        return parent::render($request, $exception);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM