且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel 5中的Ajax发布请求返回错误500(内部服务器错误)

更新时间:2021-10-12 22:58:14

虽然这个问题存在了一段时间,但没有给出可接受的答案,但我想向您指出解决方案.因为您使用的是ajax发送,并且大概仍在使用CSRF中间件,所以您需要在请求中提供一个附加的标头.

While this question exists for a while, but no accepted answer is given I'd like to point you towards the solution. Because you're sending with ajax, and presumably still use the CSRF middleware, you need to provide an additional header with your request.

向每个页面(或主版面)添加一个元标记:<meta name="csrf-token" content="{{ csrf_token() }}">

Add a meta-tag to each page (or master layout): <meta name="csrf-token" content="{{ csrf_token() }}">

并添加到您的javascript文件(或页面中的部分):

And add to your javascript-file (or section within the page):

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

请参见 https://laravel.com/docs/master/csrf #csrf-x-csrf-token 了解更多详细信息.

See https://laravel.com/docs/master/csrf#csrf-x-csrf-token for more details.