如何通过使用Ajax在LARAVEL中获得新的CSRF令牌 [英] How can I get new CSRF token in LARAVEL by using ajax

查看:205
本文介绍了如何通过使用Ajax在LARAVEL中获得新的CSRF令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个包含许多字段的表单,用户可以在其中创建无限的字段. 如果用户将更多时间花在CSRF令牌上,则该令牌将过期,并且当他单击提交LARAVEL时,将返回错误CSRF令牌不匹配. 那么,如何使用ajax调用获取新的CSRF令牌,以便可以在固定的时间间隔内更新CSRF? 我无法刷新或重新加载表单.

I have created a form which is having a lot of fields and user can create an unlimited field in it. If a user spends more time on it CSRF token get expires and when he clicks on the submit LARAVEL return the error CSRF token mismatch. So how can I get new CSRF token by using ajax call so I can update the CSRF on a regular time of interval? I can not refresh or reload the form.

推荐答案

只需将其添加到脚本中

<script type="text/javascript">
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                }
            });
</script>

并确保已将令牌添加到元标记中,如下所示.

And make sure you have added token to your meta tag like below.

<meta name="_token" content="{!! csrf_token() !!}" />

我希望这对您有用.

链接 https://laravel.com/docs/5.4/csrf#csrf-x-csrf-令牌

如果您仍然发现相同的问题,请查看以下内容

If you still found the same issue then please review these pieces of stuff

  1. 在Laravel中处理过期的令牌

并确保您查看所有答案,而不只是检查了一个答案

And Make sure you take a look at all answers, not only checked one

这篇关于如何通过使用Ajax在LARAVEL中获得新的CSRF令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆