yii2: - 如何在yii2中管理angularjs post请求

时间:2015-08-01 07:27:13

标签: angularjs yii yii2 yii2-advanced-app yii-url-manager

我正在尝试将角度控制器的发送请求发送到yii前端控制器。

这是我的 controller.js

true

这是我的yii2前端控制器

 'use strict';

define(['angular', 'd3', 'd3Cloud', 'services'], function (angular, d3) {
/* Controllers */
return angular.module('oc.controllers', ['oc.services'])
    .controller('InitCtrl', ['$scope','$http', function ($scope,$http) {


          $scope.loginFun = function() {

            var formData = {username:$scope.txtUserName, pwd:$scope.txtPassword};
            $http.post("http://localhost/yii2-angular-seed-master/frontend/web/site/login",formData).success(function(data){
              alert(data);
            });

          }             

      $scope.promos=[];
          var requestPromo = $http.get('http://localhost/yii2-angular-seed-master/frontend/web/category/promos');
          requestPromo.success(function( data ) {
            $scope.promos=data;
          });
    }])

    .config(['$httpProvider', function ($httpProvider) {
         $httpProvider.defaults.headers.post['X-CSRF-Token'] = $('meta[name="csrf-token"]').attr("content");
         $httpProvider.defaults.headers.common['Accept'] = 'application/json, text/javascript';
         $httpProvider.defaults.headers.common['Content-Type'] = 'application/json; charset=UTF-8';
    }])


 });

我在Firebug中收到此错误。

POST http://localhost/yii2-angular-seed-master/frontend/web/site/login 400错误请求

“NetworkError:400错误请求 - http://localhost/yii2-angular-seed-master/frontend/web/site/login

请为我建议代码:

 use Yii;

 class SiteController extends Controller
 {
     public function behaviors()
     {
          return [
            'access' => [
            'class' => AccessControl::className(),
            'only' => ['logout', 'signup'],
            'rules' => [
                [
                    'actions' => ['signup'],
                    'allow' => true,
                    'roles' => ['?'],
                ],
                [
                    'actions' => ['logout'],
                    'allow' => true,
                    'roles' => ['@'],
                ],
            ],
        ],
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'logout' => ['post'],
            ],
        ],
    ];
}

/**
 * @inheritdoc
 */
public function actions()
{
    return [
        'error' => [
            'class' => 'yii\web\ErrorAction',
        ],
        'captcha' => [
            'class' => 'yii\captcha\CaptchaAction',
            'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
        ],
    ];
}

public function actionIndex()
{
    return $this->render('index');
}


public function actionLogin()
{
// How to handle post request here?
// which code i have to use here?
// My angular get request is successfully work.
// But Post request not work. How can i manage it?
}




public function actionLogout()
{
    Yii::$app->user->logout();

    return $this->goHome();
}

}

2 个答案:

答案 0 :(得分:1)

代码400的响应,当您没有向GET请求发送CSRF或某些属性时发送。可能你需要修复你的$ httpProvider:

angular.module('app').config(appconfig);
appconfig.$inject = ['$httpProvider'];
function appconfig($httpProvider){
    $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    $httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name="csrf-token"]').attr('content');
}

答案 1 :(得分:0)

var app = angular.module("myApp", [], 
function($httpProvider) {
  // Use x-www-form-urlencoded Content-Type  
  $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
  $httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name="csrf-token"]').attr('content');
  $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

  /**
   * The workhorse; converts an object to x-www-form-urlencoded serialization.
   * @param {Object} obj
   * @return {String}
   */
  var param = function(obj) {
    var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

    for(name in obj) {
      value = obj[name];

      if(value instanceof Array) {
        for(i=0; i<value.length; ++i) {
          subValue = value[i];
          fullSubName = name + '[' + i + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      }
      else if(value instanceof Object) {
        for(subName in value) {
          subValue = value[subName];
          fullSubName = name + '[' + subName + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      }
      else if(value !== undefined && value !== null)
        query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
    }

    return query.length ? query.substr(0, query.length - 1) : query;
  };

  // Override $http service's default transformRequest
  $httpProvider.defaults.transformRequest = [function(data) {
    return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
  }];
});