douxuan1284 2019-01-15 20:09
浏览 108
已采纳

对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');
    }
}
  • 写回答

2条回答 默认 最新

  • dpjtn48868 2019-01-16 10:27
    关注

    Add the following code to include the csrf field in the request

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型