如何使用Angular JS发布数据?

时间:2016-01-08 09:16:48

标签: angularjs cakephp-3.0

我正在尝试将数据发布到我的应用程序,但它根本无法正常工作。在PHP我已经尝试使用CURL,我没有任何问题。

在Angular中,我正在通过控制台:

Object { data: null, status: 0, headers: headersGetter/<(), config: Object, statusText: "" }

使用Curl,我可以使用以下代码发布数据:

# the POST data 
$email = 'test@test.fr';
$password = 'blabla';

$data = array("email" => "$email", "password" => "$password", "active" => TRUE);
$data_string = json_encode($data);

$ch = curl_init('http://localhost:8888/app/api/users/register');
# An HTTP POST request 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Accept: application/json')
);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

echo $result;

使用Angular,此代码在顶部生成控制台消息:

.controller('TestCtrl', ['$scope', '$http', function($scope, $http) {

  $scope.data = {};

  $scope.newUser = function() {

      $http({
        method: 'POST',
        url: 'http://localhost:8888/app/api/users/register',
        data: {
          email:'test@test.fr',
          password:'blabla'
        },
        headers: {
          'Content-Type': 'application/json; charset=utf-8'
        }
      }).then(function successCallback(response) {
        console.log("GREAT");
      }, function errorCallback(response) {
        console.log(response)
      });

    }

}])

更多信息:

使用CURL / PHP,用户也会被创建,也是一个令牌。

string(199) "{ "success": true, "data": { "id": 18, "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjE4LCJleHAiOjE0NTI4NTIxODd9.vYU6YcuGS2rUUD2cBG233hSARWHp7dc1uBF7TdMrGeM" } }" 

通过Angular发送标题:

Accept :"application/json, text/plain, */*"
Content-Type :"application/json; charset=utf-8"
X-Requested-With :"XMLHttpRequest"

另外,我已经按照本教程创建了Cakephp 3 api: http://www.bravo-kernel.com/2015/04/how-to-build-a-cakephp-3-rest-api-in-minutes/

在Chrome上编辑:

OPTIONS http://localhost:8888/perles/app/users/register (anonymous function) @ ionic.bundle.js:23826sendReq @ ionic.bundle.js:23645serverRequest @ ionic.bundle.js:23357processQueue @ ionic.bundle.js:27879(anonymous function) @ ionic.bundle.js:27895Scope.$eval @ ionic.bundle.js:29158Scope.$digest @ ionic.bundle.js:28969Scope.$apply @ ionic.bundle.js:29263(anonymous function) @ ionic.bundle.js:62385eventHandler @ ionic.bundle.js:16583triggerMouseEvent @ ionic.bundle.js:2948tapClick @ ionic.bundle.js:2937tapMouseUp @ ionic.bundle.js:3013
(index):1 XMLHttpRequest cannot load http://localhost:8888/app/api/users/register. Response for preflight has invalid HTTP status code 500

3 个答案:

答案 0 :(得分:0)

尝试使用类似于以下内容的代码:

 $http.post("http://localhost:8888/app/api/users/register", {data: {
      email:"test@test.fr",
      password:"blabla"
    } }).success(function(){
            alert("Success!");
        });

我已经成功地使用了这个&#34; compact&#34;语法,它总是对我有用!

最佳,

布鲁诺

答案 1 :(得分:0)

好吧,试试这个模式以角度发布它是发布帖子的最佳方式:

控制器:

    .controller('TestCtrl', ['$scope', '$http', function($scope, $http) {

      $scope.data = {name:'javier',age:12};

      $scope.newUser = function() {
                var peticionjson = {};
                peticionjson['name'] = $scope.data.name;
                peticionjson['age'] = $scope.data.age;
                $http.post('http://localhost:8888/app/api/users/register', peticionjson)
                    .success(function (res) {
                        console.log(res);
                    }).error(function (error) {
                    });
            }

}

答案 2 :(得分:0)

请尝试以下操作:

var config = { headers : {'Content-Type': 'application/json; charset=utf-8'}};
//Stringify the JSON data
var data = JSON.stringify({email:'test@test.fr', password:'blabla', active: true});
$http.post(
      'http://localhost:8888/app/api/users/register', 
      data, 
      headers
  ).then( function(response){
         // success callback
  }).catch( function(error) {

  });

我更喜欢以这种方式分离成功和失败回调,它使我的代码更清晰。

现在CORS问题,似乎你的api不允许它,请确保你发送正确的访问控制标题:

Access-Control-Allow-Origin: *

使用其中一个主题的建议,我希望您的问题得到解决:

请记住,您的服务器必须允许这些api调用,然后只有Angular服务才能从中获取数据。