1

I'm trying to POST data to my application but it's simply not working. in PHP i have made some try with CURL and i don't have any issue.

In Angular, trough the console i'm getting :

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

With Curl, i can post data with the following code :

# 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;

With Angular, this code is producing the console message on the top :

.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)
      });

    }

}])

More Information :

With CURL/PHP, the user is created and a token too.

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

Header Sent trough Angular :

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

Also, i've follown this tutorial to create the Cakephp 3 api : http://www.bravo-kernel.com/2015/04/how-to-build-a-cakephp-3-rest-api-in-minutes/

EDIT , on 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
Brian Millot
  • 179
  • 11

3 Answers3

0

Try to use a code similar to the following:

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

I've successfully used this more "compact" syntax and it worked for me always!

Best,

Bruno

Bruno Oliveira
  • 735
  • 10
  • 20
0

Well, try this mode to post in angular its the best way to make a post:

CONTROLLER:

    .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) {
                    });
            }

}
Javierif
  • 632
  • 1
  • 6
  • 18
0

Try following:

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) {

  });

I prefer to separate the success and failure callbacks this way, it makes my code bit more cleaner.

Now the CORS issue, it seems your api is not allowing it, please ensure you are sending right access control headers:

Access-Control-Allow-Origin: *

Use suggestion from one of these threads, and I hope your problem should be resolved:

Remember your server must allow these api calls, then only Angular service will be able to get data from them.

Community
  • 1
  • 1
Ravish
  • 2,383
  • 4
  • 37
  • 55