对Laravel路由的JQuery POST请求抛出错误但在我直接访问时工作正常

I am trying to build a local API service for adding products to the users cart. Defined inside of my web.php file is my route for the cart:

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

If I change this to a Route::get and visit the route directly with some dummy data, it works fine and gives me

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

However, if I keep it as Route::post and then try to send a POST HTTP request from JQuery, I get this error inside of my network tab in 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": "->"
        },
        { ...

My JQuery looks like this:

$('#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.');
    });
});

My Controller function looks like this:

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');
    }
}
查看全部
douxuan1284
douxuan1284
2019/01/15 20:09
  • laravel
  • php
  • jquery
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

2个回复