【问题标题】:JQuery POST request to Laravel route is throwing errors but works fine when I directly access对 Laravel 路由的 JQuery POST 请求引发错误,但当我直接访问时工作正常
【发布时间】:2019-01-15 20:09:30
【问题描述】:

我正在尝试构建用于将产品添加到用户购物车的本地 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');
    }
}

【问题讨论】:

  • 你能展示你完整的堆栈跟踪吗? (几乎看起来当前的错误只是未能捕获原始异常。也许检查你的内核中间件,特别是阻塞 ajax 调用的东西?
  • 我开启了Routes验证,会影响吗?我的控制器中没有构建中间件,但是@JoelHarkes
  • 您是否使用 ajax POST 发送 csrf 令牌?查看how to set it up上的文档
  • 还没做,现在试试,谢谢@ljubadr

标签: php jquery laravel laravel-5


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您忘记发送csrf 字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-07
      • 1970-01-01
      • 2018-05-05
      • 1970-01-01
      • 2021-12-03
      • 2015-12-11
      • 1970-01-01
      相关资源
      最近更新 更多