запрос angularjs+cakephp с черными дырами

Я создал в UsersController метод для добавления новых пользователей в базу данных. В файлах ctp-просмотров cakephp все в порядке, так как мой запрос не содержит черных дыр. Я использую пост для этого. Но когда я перемещаю представление на angularjs, запрос становится черным. Я не понимаю. Может кто-нибудь, пожалуйста, помогите мне.

Вот код UsersController.php, функция, называемая add, делает это:

<?php

class UsersController extends AppController {

public $components = array(
    'RequestHandler',
    'Security',
    'Session',
    'Auth'
);



public function login() {

    if ($this->Session->read('Auth.User')) {
        $this->set(array(
            'message' => array(
                'text' => __('You are logged in!'),
                'type' => 'error'
            ),
            '_serialize' => array('message')
        ));
    }

    if ($this->request->is('post')) {
        if(!empty($this->request->data)){
            $userDetails = $this->User->find('first', array(
                                             'conditions' => array(
                                             'User.username' => $this->request->data['username'],
                                             'User.password' => $this->request->data['password']
                                             )));
            debug($userDetails);
            debug($this->Auth->login());
        }
        if ($this->Auth->login()) {

            $this->set(array(
                'user' => $this->Session->read('Auth.User'),
                '_serialize' => array('user')
            ));
        } else {
            $this->set(array(
                'message' => array(
                    'text' => __('Invalid username or password, try again'),
                    'type' => 'error'
                ),
                '_serialize' => array('message')
            ));
            $this->response->statusCode(401);
        }
    }
}
public function logout() {
    if ($this->Auth->logout()) {
        $this->set(array(
            'message' => array(
                'text' => __('Logout successfully'),
                'type' => 'info'
            ),
            '_serialize' => array('message')
        ));
    }
}

public function add(){

    if($this->request->is('post')){
        if(!empty($this->request->data)){
            $password = $this->request->data['User']['password'];
            $username = $this->request->data['User']['username'];
            //$password = Security::hash($this->request->data['User']['password'], 'sha1', true);

            $password = Security::hash($password.$username, 'sha1', true);
            debug($password);
        }
    }

    //$this->set(array('message',array('error' => __("No data sent")), '_serialize' => array('message')));
}
public function index() {
    $this -> user = $this -> Auth -> user();
    if ($this -> user) {
        $this -> set('users', $this -> User -> find('all'));
        $this -> set('_serialize', array('users'));
    }
    else {
        $this -> set('error', 'user not logged in');
        $this -> set('_serialize', array('error'));
    }

}

public function user($id = null) {

    $this -> layout = null;

    if (!$id) {
        throw new NotFoundException(__('Invalid user'));
    }

    $user = $this -> User -> findById($id);

    if (!$user) {
        throw new NotFoundException(__('Invalid user'));
    }
    $this -> set('user', $user);
}

}
?>

А это угловой контроллер:

angular.module('addUser.controllers', []).controller('addUserCtrl', function($scope, $http) {
$scope.register = function() {

    data = {'User':{
        'username' : $scope.username,
        'password' : $scope.password
    }};

    if(data.User.username != undefined && data.User.password != undefined){
        $http.post('API/users/add', data).success(function(data) {
        $scope.users = data.users;
        console.log(data);
    });
    }else{
        console.log('can\'t login');
    }
    /**/

};

});

PS: я новичок с cakephp. Большое спасибо и удачного кодирования ;)


person cojok    schedule 13.03.2015    source источник
comment
Видите ли вы какие-либо ошибки в консоли javascript?   -  person Austin Mullins    schedule 13.03.2015
comment
typeof(data.User.username) != "undefined" больше подходит. Кроме того, рекомендуется использовать разные имена переменных для данных запроса и ответа.   -  person Austin Mullins    schedule 13.03.2015
comment
На самом деле я увидел сейчас, что есть плохой запрос с кодом 400 для ссылки, но если я открою его в новом окне, он работает, а также если я отправлю данные из файла просмотра ctp.   -  person cojok    schedule 13.03.2015
comment
Хорошо, тогда моя следующая ставка состоит в том, что URL-адрес, сгенерированный $http.post('API/users/add', data), не соответствует вашим ожиданиям. Вы должны иметь возможность проверять сетевой трафик в инструментах вашего браузера (по крайней мере, в FF и Chrome, я не знаю о других).   -  person Austin Mullins    schedule 13.03.2015
comment
Самое интересное, что если я не использую класс безопасности cakephp, все в порядке, но мне нужно зашифровать пароль.   -  person cojok    schedule 13.03.2015


Ответы (1)


Я нашел решение проблемы, так как я просмотрел всю книгу cakephp и нашел это решение, не знаю, правильное ли оно, но для меня работает нормально. Это справочная ссылка, и для меня это было похоже на строки в книге:

public function beforeFilter() {
    $this -> Security -> blackHoleCallback = 'blackhole';

}

public function blackhole($type) {
    return $type;// don't know if it is good or bad practice like this feel free to comment
}
person cojok    schedule 16.03.2015