【问题标题】:Laravel AJAX 500 Internal Server Error, Tokens MatchLaravel AJAX 500 内部服务器错误,令牌匹配
【发布时间】:2016-02-13 21:54:06
【问题描述】:

当我提交表单时,我收到此错误并且页面会自动重新加载,但浏览器中的 url 然后会显示我在表单中发布的路线和内容。然后,如果我继续并再次提交而不重新加载页面,它就可以正常工作。可能是我没有发布令牌本身吗?我已将元标记添加到头部。

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

JS:

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

$('#postForm').submit(function(){

    var body = $('#postbody').val();
    var profileId = $('#user_id').text();

        $.ajax({
            type: "POST",
            url: "/post/"+profileId,
            data: {post:body, profile_id:profileId},
            success: function(data) {
                console.log(data);
            }
        });
});

路线:

Route::post('/post/{id}', [
    'uses' => '\App\Http\Controllers\PostController@postMessage',
    'as' => 'post.message',
    'middleware' => ['auth'],
]);

控制器:

public function postMessage(Request $request, $id)
{
    if(Request::ajax())
    {
        $this->validate($request, [
            'post' => 'required|max:1000',
        ]);

            $newMessage = Auth::user()->posts()->create([
                'body' => $request->input('post'),
                'profile_id' => $id
            ]);
    }
}

查看:

<form role="form" action="#" id="postForm">
    <div class="feed-post form-group">
        <textarea class="form-control feed-post-input" id="postbody" name="post"></textarea>
        <div class="btn-bar">
            <button type="submit" class="btn btn-default btn-post"></button>
        </div>
    </div>
    <input type="hidden" name="_token" value="{{ csrf_token() }}"/>
</form>

更新:

因此,日志显示我的控制器中“不应静态调用 Request::ajax()”。我删除了该代码,现在它工作正常。但是,我想知道是否可以删除它是否有更好的方法来解决这个问题。谢谢!

回答:通过改变来工作

if (Request::ajax()){
    // code...
}

if ($request->ajax()){
    // code...
}

【问题讨论】:

标签: ajax laravel


【解决方案1】:

将 Request::ajax() 更改为 $request->ajax()

【讨论】:

    【解决方案2】:

    你正在做一个 AJAX 帖子——你根本不应该被重定向到任何地方。如果出现错误 - 您应该只能在浏览器的开发者工具中看到它。

    尝试添加:

    $('#postForm').submit(function(e) {
        e.preventDefault();
        ...
    }
    

    这样浏览器就不会发布表单而不是您的 AJAX 调用。还可以尝试修复您的标题案例:X-CSRF-TOKEN to X-CSRF-Token

    此外,您的 postMessage() 方法根本不会返回任何内容。您可能应该将结果通知用户,或者只返回 $newMessage。

    【讨论】:

      猜你喜欢
      • 2017-04-12
      • 2020-02-12
      • 2018-04-16
      • 2016-03-24
      • 1970-01-01
      • 2019-05-12
      • 2015-09-20
      • 2023-03-04
      • 1970-01-01
      相关资源
      最近更新 更多