How to call rest API of Yii2 in Angular 7

715 Views Asked by At

I have a Angular service which makes an API call. Here is my subscribe.service.ts file

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http'

    @Injectable({
      providedIn: 'root'
    })
    export class SubscribeService {
      readonly postURL = "http://localhost/sampleproject/frontend/web/api/subscribe";
      constructor(private http:HttpClient) { }

      subscribeSubmit(subscriber){
       return this.http.post(this.postURL, subscriber);
      }
    }

The postURL which is called as an API is in yii2. Below is my ApiController.php file

            <?php
        namespace frontend\controllers;
        use Yii;
        use yii\web\Controller;

        class ApiController extends Controller {
            public $enableCsrfValidation = false;
            public static function allowedDomains() {
            return [
                 '*',                       
            ];
        }

            public function behaviors() {
            return array_merge(parent::behaviors(), [
                'corsFilter'  => [
                    'class' => \yii\filters\Cors::className(),
                    'cors'  => [
                        'Origin'                           => static::allowedDomains(),
                        'Access-Control-Request-Method'    => ['POST'],
                        'Access-Control-Allow-Credentials' => true,
                        'Access-Control-Max-Age'           => 3600,       
                    ],
                ],

            ]);
        }

             public function beforeAction($action) {
                if (\Yii::$app->getUser()->isGuest &&
                    \Yii::$app->getRequest()->url !== \yii\helpers\Url::to(\Yii::$app->getUser()->loginUrl) && Yii::$app->controller->action->id != 'subscribeforangular') {
                    \Yii::$app->getResponse()->redirect(Yii::$app->request->BaseUrl . '/../../login');
                }
                else {
                    return parent::beforeAction($action);
                }
            }

            public function actionSubscribe(){
                print_r($_POST);
            }

        }

I am trying to POST data from angular using http.post to the action "subscribe" which is in yii2, but I am getting the below error

 Access to XMLHttpRequest at 'http://localhost/sampleproject/frontend/web/api/subscribe' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The below lines are not getting added when I have checked in "Network" in console, which says that the CORS is not implemented with what I have written in controller. As per my R&D the below lines have to be added in "http://localhost/sampleproject/frontend/web/api/subscribe"

    HTTP/1.1 200 OK
    Access-Control-Allow-Credentials: true
    Access-Control-Allow-Origin: https://my-site.example.com
    Content-Type: application/json; charset=UTF-8
    Date: Fri, 24 Feb 2017 09:21:47 GMT
    Server: Apache
    Content-Length: 27
    Connection: keep-alive

I have googled the solution and implemented them, but still I am getting the same error in all the cases.

Please help !! I am trying this since 2 days. I am unable to find a proper solution and hence posted here.

0

There are 0 best solutions below