I am trying to make a http post using fetch api. Even though I am sending the token, I am getting error TokenMismatchException in VerifyCsrfToken.php . How can I make the call using fetch api? (I also tried with jQuery ajax and its working perfectly) Heres the fetch api code

我正在尝试使用fetch api制作一篇http帖子。即使我发送令牌,我在VerifyCsrfToken.php中收到错误TokenMismatchException。如何使用fetch api拨打电话? (我也尝试过使用jQuery ajax并且它的工作正常)继承人fetch api代码

      var URL = $("#form").attr("action");
      var token = $("input[name='_token']").val();
      var group_id = $(this).val();
  fetch(URL, {
       method: 'post',
       mode: 'no-cors',
       body: JSON.stringify({
           'csrf-token': token,
           'group_id': group_id
       })
     }).then(function(response){
           return response.json();
       })  .then(function(json){



       })
         .catch(function(error){


         });

I have added token in form like this

我已经在这样的表单中添加了令牌

<form id="form" action="{{ url('api/getcoursebygroup') }}">
    <input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" />
  </form>

This jQuery ajax call is working fine :

这个jQuery ajax调用工作正常:

$.ajax({
          type: "POST",
          url:  URL,
          data: { "group_id" : group_id, "_token" : token },
          dataType: 'json'
      }).done(function (result) {

        if(result.code == 1){



        }


      });

jQuery ajax call headers

jQuery ajax调用头文件

Fetch api call headers

获取api调用头

4 个解决方案

#1


9

Finally I was able to make it work :)

最后我能够让它工作:)

There were 2 changes I have to make

我必须做出两项改变

1) Fetch Api don't use cookie by default. So to make it use cookie I added

1)Fetch Api默认情况下不使用cookie。所以要使用我添加的cookie

credentials: "same-origin"

凭证:“同源”

2)the data need to be submitted in Form data format rather than json

2)数据需要以表格数据格式而不是json格式提交

so here's my working code

所以这是我的工作代码

       var URL = $("#form").attr("action");
       var token = $("input[name='_token']").val();
       var group_id = $(this).val();

      fetch(URL, {
       method: 'post',
       credentials: "same-origin",
       body: new FormData(document.getElementById('form'))
     }).then(function(response){
           return response.json();
       })  .then(function(json){

         // change course

       })
         .catch(function(error){


         });

更多相关文章

  1. 循环不能正常工作 - 守夜人
  2. 无法让.click()在禁用的textarea上工作
  3. Vue js v-bind不工作?
  4. JQuery 1.4.4和Datatable 1.7不工作
  5. 单击它时,为什么下拉菜单不在我的导航栏中工作?
  6. 为什么jquery click事件在plunker中工作但在任何浏览器中都没有
  7. AngularJS身份验证和基于XSRF令牌
  8. setInterval在Chrome上不能正常工作
  9. 单选按钮单击,隐藏/显示不工作

随机推荐

  1. Android(安卓)通知栏Notification的整合
  2. Shiro安全框架(1)入门基础案例
  3. 测试 Android(安卓)G1 是否支持 OpenGL
  4. java多线程(3)Thread构造函数解析
  5. 聊聊java中的进制问题
  6. 面试官:手写一个快速排序,并对其改进
  7. java集合系列(10)Hashtable源码分析(jdk1.8,
  8. java网络编程(5)解决阻塞问题的NIO编程
  9. 队列(链式)
  10. 一文彻底看懂Base64原理(并使用java实现)