如何在Laravel中使用jQuery ajax请求自动添加X-CSRF-TOKEN [英] How to automatically add X-CSRF-TOKEN with jQuery ajax request in Laravel

查看:1573
本文介绍了如何在Laravel中使用jQuery ajax请求自动添加X-CSRF-TOKEN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何自动添加我的Laravel应用程序的ajax请求(GET或POST)的csrf令牌,而无需手动添加到每个请求。

How can I add csrf token with my ajax requests (GET or POST) of my Laravel application automatically without adding it manually to each and every request.

我的ajax请求

   $.ajax({
      type:'post',
      url: "/email/unique",
      data: { "_token": "{{ csrf_token() }}", "email": email }
      success: function(data) {
        console.log(data);
      }
   });


推荐答案

在Laravel中 csrf-的值令牌元标记默认情况下使用Axios HTTP库进行注册。但如果您 不使用此库 ,则需要为您的应用程序手动配置此行为。

In Laravel the value of the csrf-token meta tag registers by default with the Axios HTTP library. But If you are not using this library, you will need to manually configure this behavior for your application.

为此,请将令牌存储在HTML元标记中

To do this, store the token in a HTML meta tag


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

然后,一旦你创建了元标记,您可以指示jQuery库自动将令牌添加到所有请求标头。

Then, once you have created the meta tag, you can instruct the jQuery library to automatically add the token to all the request headers.

为此,将代码添加到 resources / js / bootstrap.js 文件Laravel 5.7 resources / assets / js / bootstrap.js for Laravel 5.6 及以下版本。

For that add the code to the resources/js/bootstrap.js file for Laravel 5.7 and resources/assets/js/bootstrap.js for Laravel 5.6 and below versions.

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

没有csrf令牌的Ajax,因为它会自动添加

Ajax without csrf token as it will get added automatically

$.ajax({
      type:'post',
      url: "/email/unique",
      data: { "email": email }
      success: function(data) {
        console.log(data);
    }
 }); 

这篇关于如何在Laravel中使用jQuery ajax请求自动添加X-CSRF-TOKEN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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