php laravel 5 中的 ajax 帖子返回错误 500(内部服务器错误)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30154489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:34:42  来源:igfitidea点击:

ajax post in laravel 5 return error 500 (Internal Server Error)

phpjqueryajaxlaravellaravel-5

提问by Juliver Galleto

this is my test ajax in laravel 5 (refer below)

这是我在 Laravel 5 中的测试 ajax(请参阅下文)

$("#try").click(function(){
    var url = $(this).attr("data-link");
    $.ajax({
        url: "test",
        type:"POST",
        data: { testdata : 'testdatacontent' },
        success:function(data){
            alert(data);
        },error:function(){ 
            alert("error!!!!");
        }
    }); //end of ajax
});

and the trigger link

和触发链接

<a href="#" id="try" data-link="{{ url('/test') }}">Try</a>

and my route

还有我的路线

Route::post('test', function()
{
    return 'Success! ajax in laravel 5';
});

but it gives me error when I run the console in google chrome and it doesnt return the expected response "return 'Success! ajax in laravel 5';"

但是当我在谷歌浏览器中运行控制台时它给了我错误并且它没有返回预期的响应“返回'成功!ajax in laravel 5';”

POST http://juliver.laravel.com/test500 (Internal Server Error)

POST http://juliver.laravel.com/test500(内部服务器错误)

whats wrong/problem to my code? anything im missing?

我的代码有什么问题/问题?我缺少什么?

回答by Ben Fransen

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.

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

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

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

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

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

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

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

有关更多详细信息,请参阅https://laravel.com/docs/master/csrf#csrf-x-csrf-token

回答by Meta Pakistani

90% of the laravel ajax internal server error is due to missing CSRF token. other reasons can inlucde:

90% 的 Laravel ajax 内部服务器错误是由于缺少 CSRF 令牌。其他原因可能包括:

  • Wrong Request Type (e.g sending post to get)
  • Wrong data type recived (e.g ajax is expecting JSON and app returns string)
  • Your .htaccess is misconfigured
  • Missing Route
  • Code Error
  • 错误的请求类型(例如发送帖子以获取)
  • 收到错误的数据类型(例如,ajax 需要 JSON 并且应用程序返回字符串)
  • 您的 .htaccess 配置错误
  • 缺少路线
  • 代码错误

You can read further about this in details here: https://abbasharoon.me/how-to-fix-laravel-ajax-500-internal-server-error/

您可以在此处详细了解此内容:https: //abbasharoon.me/how-to-fix-laravel-ajax-500-internal-server-error/

回答by Khan Shahrukh

I guess this has been solved by now but still the best thing to do here is to send the token with your form

我想这已经解决了,但在这里做的最好的事情仍然是将令牌与您的表单一起发送

{!! csrf_field() !!}

and then in your ajax

然后在你的 ajax 中

$("#try").click(function(){
var url = $(this).attr("data-link");
$.ajax({
    url: "test",
    type:"POST",
    data: { '_token': token, 'someOtherData': someOtherData },
    success:function(data){
        alert(data);
    },error:function(){ 
        alert("error!!!!");
    }
}); //end of ajax
});

回答by aethergy

In App\Http\Middleware\VerifyCsrfToken.php you could try updating the file to something like:

在 App\Http\Middleware\VerifyCsrfToken.php 中,您可以尝试将文件更新为以下内容:

class VerifyCsrfToken extends BaseVerifier {

    private $openRoutes =
    [
        ...excluded routes
    ];

    public function handle($request, Closure $next)
    {
        foreach($this->openRoutes as $route)
        {
            if ($request->is($route))
            {
                return $next($request);
            }
        }

        return parent::handle($request, $next);
    }
};

This allows you to explicitly bypass specific routes that you do not want verified without disabling csrf validation globally.

这允许您在不全局禁用 csrf 验证的情况下显式绕过您不想验证的特定路由。

回答by Danish Jamshed

You can add your URLs to VerifyCsrfToken.php middleware. The URLs will be excluded from CSRF verification.

您可以将您的 URL 添加到 VerifyCsrfToken.php 中间件。这些 URL 将被排除在 CSRF 验证之外。

protected $except = [
    "your url",
    "your url/abc"
];

回答by Sayed Khan Prince

you have to pass the csrf field through ajax please look at the code here

你必须通过ajax传递csrf字段请看这里的代码

$.ajax({
                                        type: "POST",
                                        url:'{{URL::to("/delete-specialist")}}',
                                        data: {
                                            id: id,

                                            _token: $('#signup-token').val()
                                        },
                                        datatype: 'html',
                                        success: function (response) {
                                            if(response=="deleted"){
                                                $("#"+id).hide();
                                                $("#message").html("successfully deleted");
                                            }

                                        }

                                    });

and you also need to write this input field before this

并且您还需要在此之前编写此输入字段

<input id="signup-token" name="_token" type="hidden" value="{{csrf_token()}}">

still if you do not understand please enjoy this video https://www.youtube.com/watch?v=ykXL8o0slJA&t=20s

如果你还是不明白,请欣赏这个视频 https://www.youtube.com/watch?v=ykXL8o0slJA&t=20s

回答by Setmax

for me this error cause of different stuff. i have two ajax call in my page. first one for save comment and another one for save like. in my routes.php i had this:

对我来说,这个错误是由不同的东西引起的。我的页面中有两个 ajax 调用。第一个用于保存评论,另一个用于保存喜欢。在我的 routes.php 我有这个:

Route::post('posts/show','PostController@save_comment');
Route::post('posts/show','PostController@save_like');

and i got 500 internal server error for my save like ajax call. so i change second line http request type to PUT and error goes away. you can use PATCH too. maybe it helps.

我在保存时遇到了 500 个内部服务器错误,例如 ajax 调用。所以我将第二行 http 请求类型更改为 PUT 并且错误消失了。您也可以使用 PATCH。也许它有帮助。

回答by cescgie

Using post jquery instead helped me to solve this problem

使用 post jquery 帮助我解决了这个问题

$.post('url', data, function(response) {
    console.log(response);
});

回答by Bostjan

By default Laravel comes with CSRF middleware.

默认情况下,Laravel 带有 CSRF 中间件。

You have 2 options:

您有 2 个选择:

  1. Send token in you request
  2. Disable CSRF middleware (not recomended): in app\Http\Kernel.php remove VerifyCsrfToken from $middleware array
  1. 在您的请求中发送令牌
  2. 禁用 CSRF 中间件(不推荐):在 app\Http\Kernel.php 中从 $middleware 数组中删除 VerifyCsrfToken

回答by Ashwani Garg

Short and Simple Solution

简短而简单的解决方案

e.preventDefault();
var value = $('#id').val();
var id = $('#some_id').val();
url="{{url('office/service/requirement/rule_delete/')}}" +"/"+ id;
console.log(url);
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
$.ajax({
/* the route pointing to the post function */
    url: url,
    type: 'DELETE',
/* send the csrf-token and the input to the controller */
    data: {message:value},
    dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
    success: function (data) { 
    console.log(data)
    //$('.writeinfo').append(data.msg);
    //$('#ruleRow'+id).remove();
    }
});
return false;