Laravel 5 App-AJAX发布请求不接受令牌并引发500个内部服务器错误

时间:2018-07-28 03:18:30

标签: php jquery ajax laravel laravel-5

因此,在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发布请求)。

2 个答案:

答案 0 :(得分:2)

首先在storage/logs/laravel.log中查找异常堆栈跟踪。这样应该可以更清楚地表明发生了什么。

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

500个ISE的常见原因是无法通过use导入类。

答案 1 :(得分:0)

像这样使用它:-

headers: {
        'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
相关问题