0

I have create angular2 application and REST api in yii2.

Yii2 controller is "yii\rest\Controller"

Angularjs and Angular2 both are very different.

I don't understand how to use CSRF token in angular2 post request.

Angular2 and yii2 no any connection. only api call in yii2.

Bharat Chauhan
  • 3,204
  • 5
  • 39
  • 52

1 Answers1

0

in your SiteController Add this function to show your csrf token

public function actionCsrf()
{
    Yii::$app->response->format = Response::FORMAT_JSON;
    return [
        '_csrf' => Yii::$app->request->csrfToken
    ];
}

and add input type hidden in your form like on html

<form>
...
<input type="hidden" name="_csrf" id="_csrf" value="" />
...
</form>

make get ajax in your angular, its version on jquery on javascript

<script type="text/javascript">
    $.ajax({
        type : "GET",
        data : "",
        dataType: 'json',
        contentType: "application/json",
        url : "http://localhost/app/web/site/csrf",
        success : function(result){
            var resultObj = result;
            document.getElementById("_csrf").value = resultObj._csrf;
        }
    });
</script>
Arbahud Rio Daroyni
  • 3,663
  • 2
  • 9
  • 8