代码之家  ›  专栏  ›  技术社区  ›  Jaquarh

jquery post对laravel路由的请求正在抛出错误,但在我直接访问时工作正常

  •  0
  • Jaquarh  · 技术社区  · 6 年前

    我正在尝试构建本地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的network选项卡中得到这个错误:

    {
        "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 回复  |  直到 6 年前
        1
  •  0
  •   christopher_bincom    6 年前

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

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    
        2
  •  0
  •   Elmar Abdurayimov    6 年前

    你忘了寄了 csrf 字段。