在laravel中的Http Post使用fetch api给出TokenMismatchException

Abh*_*mar 10 javascript jquery laravel fetch-api

我正在尝试使用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){


         });
Run Code Online (Sandbox Code Playgroud)

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

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

这个jQuery ajax调用工作正常:

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

        if(result.code == 1){



        }


      });
Run Code Online (Sandbox Code Playgroud)

jQuery ajax调用头文件

在此输入图像描述

获取api调用头

在此输入图像描述

Abh*_*mar 12

最后我能够使它工作:)

我必须做出2项改变

1)获取Api默认情况下不使用cookie.所以要使用我添加的cookie

credentials: "same-origin"

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

所以这是我的工作代码

       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){


         });
Run Code Online (Sandbox Code Playgroud)

  • 声明的token用在哪里? (7认同)

小智 9

我可能迟到了,但这也有效

    fetch("/audio/signed", {
      headers: {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "X-Requested-With": "XMLHttpRequest",
        "X-CSRF-Token": $('input[name="_token"]').val()
      },
      method: "post",
      credentials: "same-origin",
      body: JSON.stringify({
        key: "value"
      })
    })
Run Code Online (Sandbox Code Playgroud)


Umu*_*maz 9

index.blade.php

<meta name="csrf-token" content="{{ csrf_token() }}">
Run Code Online (Sandbox Code Playgroud)

应用程序.js

const csrfToken = document.head.querySelector("[name~=csrf-token][content]").content;

function orderPost(order) {
    fetch('/orders', {
        method: 'post',
        body: JSON.stringify(order),
        headers: {
            'Content-Type': 'application/json',
            "X-CSRF-Token": csrfToken
        }
    })
    .then(response => {
        return response.text();
    })
    .then(text => {
        return console.log(text);
    })
    .catch(error => console.error(error));
};
Run Code Online (Sandbox Code Playgroud)

订单控制器.php

public function store(Request $request){
    $order = new Order();
    $order->user_id = $request->json('user_id');
    $order->item_list = $request->json('item_list');
    $order->leave_note = $request->json('leave_note');
    $order->total = $request->json('total');
    $order->save();

    $response = [
        'status' => 'success',
        'message' => 'order stored',
];

    return response()->json($response);
}

Run Code Online (Sandbox Code Playgroud)