到Laravel路线的jQuery POST请求抛出错误,但是当我直接访问

时间:2019-01-15 20:09:31

标签: php jquery laravel laravel-5

我正在尝试构建本地API服务,以将产品添加到用户购物车。在我的web.php文件中定义的是我的购物车路线:

Route::post('/cart', 'SessionController@addOrUpdate')->name('Cart');

如果我将其更改为Route::get并使用一些虚拟数据直接访问该路线,那么它可以正常工作并给我

{"status":true,"cart":{"4":[{"productName":"foo","quantity":1}]}}

但是,如果我将其保留为Route::post,然后尝试从JQuery发送POST HTTP请求,则会在chrome的“网络”标签中收到此错误:

{
    "message": "",
    "exception": "Symfony\\Component\\HttpKernel\\Exception\\HttpException",
    "file": "C:\\xampp\\htdocs\\iezonsolutions\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Exceptions\\Handler.php",
    "line": 204,
    "trace": [
        {
            "file": "C:\\xampp\\htdocs\\iezonsolutions\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Exceptions\\Handler.php",
            "line": 176,
            "function": "prepareException",
            "class": "Illuminate\\Foundation\\Exceptions\\Handler",
            "type": "->"
        },
        { ...

我的JQuery看起来像这样:

$('#add-to-cart').click(function() {
    $.post('{{ route('Cart') }}', { productName: '{{ $product->title }}', productId: {{ $product->id }} }, function(response) {
        if(response) {
            $('#add-to-cart').notify('Successfully added to your cart.', 'success');
            return;
        }
        $('#add-to-cart').notify('An error has occured please try again.');
    });
});

我的控制器功能如下:

public function addOrUpdate(Request $request) {

    if(!isset($request->productName) && !isset($request->productId)) {
        return response(['status' => false], 200)
              ->header('Content-Type', 'application/json');
    }

    # TODO: Check productID/productName exists in DB


    # Init cart if not yet set
    if(!session()->has('cart')) {
        session()->put('cart', []);
        session()->flash('cart');
    }

    if(isset(session('cart')[$request->productId])){
        # Pull and delete the old value
        $product = session()->pull("cart.{$request->productId}", "cart.{$request->productId}");

        # If we managed to pull anything, lets increase the quantity
        if(isset($product)) {
            if($request->has('delete')) {
                $product[0]['quantity']--;
            } else {
                $product[0]['quantity']++;
            }

            # If quantity has not fallen below 1 do not add
            if($product[0]['quantity'] > 0)
                session()->push("cart.{$request->productId}", $product[0]);

            session()->reFlash('cart');

            return response(['status' => true, 'cart' => session('cart')], 200)
              ->header('Content-Type', 'application/json');
        }

        # This should never hit this - but just in-case
        return response(['status' => false], 204)
              ->header('Content-Type', 'application/json');

    } else {

        # If it contains delete - do not add
        if($request->has('delete'))
            return response(['status' => true, 'cart' => session('cart')], 200)
              ->header('Content-Type', 'application/json');

        # Nothing was pulled, lets add it
        session()->push("cart.{$request->productId}",  [
            'productName'   => $request->productName,
            'quantity'      => 1
        ]);

        session()->reFlash('cart');

        return response(['status' => true, 'cart' => session('cart')], 200)
              ->header('Content-Type', 'application/json');
    }
}

2 个答案:

答案 0 :(得分:0)

您忘记发送csrf字段。

答案 1 :(得分:0)

添加以下代码以在请求中包含csrf字段

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