Laravel 5 App - AJAX Post请求不接受令牌并抛出500内部服务器错误

问题描述 投票:1回答:2

所以,我一直在这里寻找3小时的好时间,为什么我的代码不起作用。即使我尝试过多种方法来实现它,我也不认为我的ajax请求正在检测我的CSRF令牌。 AJAX请求新手,所以很容易。

目标:向/ email / subscribe /提交ajax POST请求,并将用户提供的电子邮件地址添加到email_subscribers表中。

我已经尝试将以下内容添加到我的代码中以显示令牌:

元标记和Ajax设置。

文件顶部

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

在脚本标签INSIDE中jquery $(document).ready()函数

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

隐藏的输入字段

我还添加了一个隐藏的输入字段,并尝试将标记插入ajax帖子内的数据对象中。

HTML

<input type="hidden" id="token" value="{{ csrf_token() }}">

Javascript标记

var token = $('#token').val();
// var token = $('meta[name="csrf-token"]').attr('content'); //Tried this way

$.ajax({
    type: 'POST',
    url: '/email/subscribe/',
    dataType: 'json',
    data: {
        email: email,
        '_token': token,
        // "_token": "{{ csrf_token() }}", //Tried this way as well
        "_method": 'POST',
    },
    success: function (data) {
        // Check Server Side validation
        if($.isEmptyObject(data.errors)){
            console.log(data['success']);
        }else{
            // Validation Failed Display Error Message
            console.log(data.errors);
        }

    },
    error: function (data) {
        console.log(data);
    }
}); // End Ajax POST function

这是我的web.php文件

// Email Routes
Route::prefix('email')->group(function() {

    // Create Post Route for subscribing
    Route::post('/subscribe', 'EmailSubscriptionsController@subscribe')->name('email.subscribe');

});

和我的EmailSubscriptionsController

class EmailSubscriptionsController extends Controller
{
    // Store the Email into the database
    public function subscribe(Request $request) {

        // Validate the request
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
        ]);

        // If the validation fails
        if($validator->fails()) {
            return response()->json([
                'errors' => $validator->errors()->all(),
            ]);
        }

        // New Section Object
        $subscription = new EmailSubscription;

        // Add Name into Section Object
        $subscription->email = $request->email;

        // Save the Section
        $subscription->save();

        // Return The Request
        return response()->json([
            'success' => 'Record has been saved successfully!'
        ]);
    } // End Subscribe

} // End Controller

真的很奇怪的事实是,当我用NOTHING提交请求时,我的subscribe()函数中的以下内容:

// Return The Request
    return response()->json([
        'success' => 'Record has been saved successfully!'
    ]);

它不会返回错误....只需将成功消息传递给控制台即可。我不确定我做错了什么,因为我在我的网站的另一部分工作(ajax post请求)。

php jquery ajax laravel laravel-5
2个回答
2
投票

首先查看storage/logs/laravel.log以获取异常堆栈跟踪。这应该更清楚地表明失败的原因。

Web检查器还允许您查看通常包含跟踪的响应。

500 ISE的一个常见原因是通过use不正确地导入类。


0
投票

使用它像这样: -

headers: {
        'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
© www.soinside.com 2019 - 2024. All rights reserved.