1

我有个问题。

我想使用 cakephp(后端)和 angular js(前端)创建一个应用程序。

我对来自 Angular js 的登录用户一无所知。

我的代码:

后端 - 应用控制器

class AppController extends Controller {

    public $components = array(
        'Session',
        'RequestHandler',
        'Cookie',
        'Auth' => array(
            //'loginRedirect'   => array('controller' => 'index', 'action' => 'home'),
            //'logoutRedirect'=> array('controller' => 'index', 'action' => 'home'),
                'authenticate'  => array(
                'Form' => array(
                    'fields'    => array('username' => 'username', 'password' => 'password', 'status' => 'enabled'),
                    'userModel' => 'User',
                    'scope'     => array('User.status' => 'enabled')
                )
            )
        )
    );

    public $helpers = array ('Html','Session','Js','Form');

}

后端 - 用户控制器

class UsersController extends AppController {

    public function beforeFilter() {

        $this->Auth->allow('register');

        $this->Auth->fields = array(
            'username'          => 'username',
            'password'          => 'secretword',
        );
    }

    public function login() {

        if ($this->request->is('post')) {

            if ($this->Auth->login()) {
                $this->User->id = $this->Auth->user('id');
                $this->User->saveField('last_login', date('Y-m-d H:i:s') );
                die("Logged");
            }
        }
        throw new ForbiddenException("You are not authorized to access that location.");

    }

前端 - userSv

var login = function(data) {

    var deferred = $q.defer();

    var params = {
        "params":{
            "plugin":null,
            "controller":"users",
            "action":"login",
            "named":[],
            "pass":[],
            "isAjax":false              
        },
        "data":{"User":{"username":data.username,"password":data.password}},
        "query":[],
        "url":"users\/login",
        "base":"",
        "webroot":"\/",
        "here":"\/users\/login"
    };

    console.log(params);

    $http({method: 'POST', url: '/users/login',data:params}).
    success(function(data, status, headers, config) {
        console.log("success");
        //console.log(data);
        console.log(status);
        console.log(headers);
        console.log(config);
    }).
    error(function(data, status, headers, config) {
        console.log("error");
        //console.log(data);
        console.log(status);
        console.log(headers);
        console.log(config);
    });

    return deferred.promise;
}

所以,发送信息后,我得到:

“您无权访问该位置。

错误:在此服务器上找不到请求的地址“/users/login”。”

你有什么主意吗?

4

1 回答 1

0

我编写了一些代码,其中有一个 Angular 应用程序向后端 CakePHP 服务器发出 JSON 请求,并且身份验证由插件处理。我认为这正是您正在寻找的。需要注意的是,我不使用内置的 CakePHP Auth 组件,而是自己编写的。

是代码,自述文件包含概念。

于 2015-01-13T06:59:01.063 回答