且构网

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

laravel 5 中的 Ajax post 请求返回错误 500(内部服务器错误)

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

虽然这个问题存在了一段时间,但没有给出公认的答案,我想为您指出解决方案.因为您使用 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.