Laravel 5.5 ajax 调用 419(未知状态)

新手上路,请多包涵

我做了一个ajax调用,但我不断收到这个错误:

419(未知状态)

不知道是什么原因导致我在其他帖子上看到它必须使用 csrf 令牌做一些事情,但我没有表格所以我不知道如何解决这个问题。

我的电话:

 $('.company-selector li > a').click(function(e) {
     e.preventDefault();

     var companyId = $(this).data("company-id");

      $.ajax({
          headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
          url: '/fetch-company/' + companyId,
          dataType : 'json',
          type: 'POST',
          data: {},
          contentType: false,
          processData: false,
          success:function(response) {
               console.log(response);
          }
     });
  });

我的路线:

 Route::post('fetch-company/{companyId}', 'HomeController@fetchCompany');

我的控制器方法

/**
 * Fetches a company
 *
 * @param $companyId
 *
 * @return array
 */
public function fetchCompany($companyId)
{
    $company = Company::where('id', $companyId)->first();

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

最终目标是在 html 元素中显示响应中的某些内容。

原文由 Chris 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 630
2 个回答

在头部使用这个:

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

并在 ajax 中获取 csrf 令牌:

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

请参考 Laravel 文档 csrf_token

原文由 Kannan K 发布,翻译遵循 CC BY-SA 4.0 许可协议

以宇宙程序员的名义

我用纯 js 发送 ajax,我明白当我没有在纯 js 中设置这种 ajax 方法 << xhr.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”) >> 我收到这个错误419.

纯ajax的完整方法是:

让 token = document.querySelector(‘meta[name=“csrf-token”]’).content;

让 xhr = new XMLHttpRequest();

 // Open the connection
xhr.open("POST", "/seller/dashboard/get-restaurants");

// 你必须在代码中设置这一行(如果你没有设置你会收到错误 419):

 xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//* Set up a handler for when the task for the request is complete
xhr.onload = function () {

};

// Send the data.
xhr.send(`_token=${token}`);

原文由 God is universe programmer 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题