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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀