如何在 Laravel 的外部 js 文件中包含 csrf_token()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30686266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:43:41  来源:igfitidea点击:

How to include csrf_token() in an external js file in Laravel?

javascriptphpjquerylaravellaravel-5

提问by Faizuddin Mohammed

Initially, I wrote all the JavaScript code right in my HTML page using the <script>tag.

最初,我使用<script>标签在我的 HTML 页面中编写了所有 JavaScript 代码。

A post call in jQuery in the JavaScript was something like this.

JavaScript 中 jQuery 中的 post 调用是这样的。

$.post('store',{'_token':'{{csrf_token()}}'}, function(data){ /*a bunch of code*/ });

The code worked fine. But, later I put all my script into an external js file. And the code is not working anymore.

代码运行良好。但是,后来我将所有脚本都放入了一个外部 js 文件中。并且代码不再起作用。

I have the problem with the {{csrf_token()}}, the error being

我有问题{{csrf_token()}},错误是

TokenMismatchException in compiled.php

compiler.php 中的 TokenMismatchException

What should I do if I want to external js files with Laravel?

如果我想用 Laravel 外部 js 文件我该怎么做?

回答by Limon Monte

  1. add <meta>tag with the token to the blade layout:
  1. <meta>带有令牌的标签添加到刀片布局:
<meta name="_token" content="{{ csrf_token() }}">
  1. setup ajax requests:
  1. 设置ajax请求:
$(function() {
  $.ajaxSetup({
    headers: {
      'X-CSRF-Token': $('meta[name="_token"]').attr('content')
    }
  });
});

Now you can use $.post()without providing _tokeneach time.

现在您$.post()无需_token每次都提供即可使用。