首页 > 解决方案 > 无法在具有 laravel 和 Angular 的站点上的 api 请求中动态设置 cookie

问题描述

大家好,我有一个应用程序,我需要在其中发出 API 请求,并且该应用程序由 laravel 和 Angular 组成。Laravel 用于后端,Angular 用于前端。API 用于为用户订阅特定任务。在我的应用程序上,我需要发出一个 API 请求,该请求需要从后端生成的 cookie(很可能我不确定)。因此,这些 cookie 使我的 API 能够正常工作。我已经准备好了所有的东西,但是I can't set the cookies dynamically。问题是我不确定这些 cookie 是从哪里生成的。我创建了一个自定义函数,该函数使用某些特定参数调用 API,然后它只是以用户订阅的权限订阅用户。
我的应用程序工作流程如下

在最后一步,我无法获得让用户订阅他们支付的计划所需的 cookie。这次我需要从 API 中获取 cookie,我可以通过手动发出请求来获取该 cookie。因为这是一个付款程序,我不能让它手动完成,整个过程需要自动进行。

我的 API 没问题The problem is that I can not make the cookies dynamically and also I am not being able to use those dynamically generated cookies each time a request is made

/**
         * Create a new subscription.
         *
         * @return JsonResponse
         */
        public function store()
        {
            $this->authorize('update', Subscription::class);

            $this->validate($this->request, [
                'user_id' => 'required|exists:users,id|unique:subscriptions',
                'renews_at' => 'required_without:ends_at|date|nullable',
                'ends_at' => 'required_without:renews_at|date|nullable',
                'plan_id' => 'required|integer|exists:billing_plans,id',
                'description' => 'string|nullable',
            ]);

            $subscription = $this->subscription->create($this->request->all());

            return $this->success(['subscription' => $subscription]);
            console.log('running');
        }



    public function apicall(Request $request){
            $curl = curl_init();
            $xsrf_token = request()->Cookie("X-XSRF-TOKEN");
            $cookie = request()->Cookie("Cookie");

            curl_setopt_array($curl, array(
                CURLOPT_URL => 'localhost:4200/secure/billing/subscriptions',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS =>'{
                      "user_id": 3,
                      "renews_at": "2021-01-29 18:00:00",
                      "plan_id": 1,
                      "description": "null"
              }',
                CURLOPT_HTTPHEADER => array(
                  $xsrf_token,
                  $cookie,
                  'Host: localhost:4200',
                  'Referer: http://localhost:4200/admin/subscriptions?page=1&per_page=15',
                  'Origin: http://localhost:4200',
                  'Content-Type: application/json'
                ),
              ));
              
            $response = curl_exec($curl);
            curl_close($curl);
            return redirect('http://localhost:4200/dashboard')->with('status', 'Success');    
        }

标签: phplaravelcookies

解决方案


推荐阅读