使用 Axios Post 时未找到购物车会话

我正在尝试使用bumbummen99/LaravelShoppingcart实现购物车功能,用户可以在其中增加/减少购物车中的商品数量。按“+”或“-”会触发一个名为updateCart()的 onclick javascript 函数。


updateCart()使用Axios向我的 CartController@updateCart() 发送一个发布请求,我在其中运行逻辑来更新购物车数量。


问题:提交发布请求后,我无法访问全局购物车会话。


一旦我在 CartController 中的 updateCart() 中,我可以成功地从 axios 访问请求变量。但是,我无法访问我的购物车会话。即使我有正确的 rowId,我也找不到购物车物品。


我的购物车中有商品,但键入 Cart::content() 或 Cart::get() 返回错误 500,因为它认为我的购物车是空的。


一旦我可以检索到我的购物车,我就可以使用 Cart::update() 等实现更新数量的逻辑。请帮助!


点击 + 或 - 触发 updateCart(action,rowId)


<script src="https://unpkg.com/axios/dist/axios.min.js"></script>


<script>

    function updateCart(action,rowId) {

        axios.post('/api/update-cart', {

            action: action,

            rowId: rowId

        }).then(response => console.log(response)).catch(error => {

            console.log(error.response)

        });

    }

</script>

api.php


Route::post('update-cart', 'CartController@updateCart')->name('update-cart');

购物车控制器.php


public function updateCart(Request $request) {


    //works, returns '620d670d95f0419e35f9182695918c68'

    return $request->get('rowId');


    //works, returns 'add' or 'subtract'

    return $request->get('action');


    //fails, returns empty array

    return Cart::content();


    //fails, error 500 because cannot find cart instance

    return Cart::get('620d670d95f0419e35f9182695918c68');


    return 200;

}

运行时,我无法访问 Cart::content() 和相关的 Cart 函数。它试图返回应该显示我的整个购物车的 Cart::content()。

http://img2.mukewang.com/62c9381c000185fb09050757.jpg

这是我在任何其他页面上返回 Cart::content()


http://img3.mukewang.com/62c938260001c0b610920162.jpg

隔江千里
浏览 161回答 2
2回答

慕勒3428872

我建议您在数据库中使用购物车。假设有人在网络上使用您的 api,然后他被添加到购物车。第二天他回到您的商店,但使用移动应用程序。所以如果我们使用会话,我认为它不能使用 api。但如果使用数据库,您可以根据用户 ID 权限存储购物车数据库。

慕慕森

您无法访问 API 路由中的会话。API 基于令牌,而不是会话。阅读“JWT”(JSON Web 令牌)或“OAuth”或“Laravel Passport”。如果您真的想要,您仍然可以强制执行会话:打开app/Http/Kernel.php寻找protected $middlewareGroups =你应该看到的地方'api' => [只需添加以下内容:&nbsp;\App\Http\Middleware\EncryptCookies::class,
打开App,查看更多内容
随时随地看视频慕课网APP