【发布时间】:2017-11-14 10:38:57
【问题描述】:
我正在尝试从角度控制器向 yii 前端控制器发送 post 请求。
这是我的 controller.js
'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';
}])
});
这是我的 yii2 前端控制器。
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();
}
}
我在 Firebug 中遇到此错误。
发布http://localhost/yii2-angular-seed-master/frontend/web/site/login 400 错误请求
“网络错误:400 错误请求 - http://localhost/yii2-angular-seed-master/frontend/web/site/login”
请给我推荐一个代码:
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?
}
【问题讨论】:
-
你的配置文件呢?您可以将其添加到您的问题中吗?您是否将您的应用程序配置为期望 Json Post Request ?有没有理由不使用 Yii's built in RESTful Web Service APIs ?它已经有stateless Authentication Support
标签: angularjs yii yii2 yii2-advanced-app yii-url-manager