0
votes

I am trying to make a POST request from my Ionic Project in angular to my Laravel Dingo API. When I make the POST request in POSTMAN, it successfully creates a new record, but when I do it in Angularjs, it returns the response for the GET request.

This the response POSTMAN suggests for the code for Jquery:

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://app.extremenazarene.org/api/contacts",
  "method": "POST",
  "headers": {
    "authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6XC9cL2FwcC5leHRyZW1lbmF6YXJlbmUub3JnXC9hcGlcL2xvZ2luIiwiaWF0IjoxNDY0NjM1NDQwLCJleHAiOjE0NjQ2MzkwNDAsIm5iZiI6MTQ2NDYzNTQ0MCwianRpIjoiYmZjMTc3YzdhODk5OGE1Y2Q1NWRiYjIzOTU4YzQ5YzMifQ.fdiGmKy9ipPnvdLuapFFe8Rz6nD7ty-gkzfWq8ySO_U",
    "cache-control": "no-cache",
    "postman-token": "c022a35b-bbdd-2f77-f7b9-2802340dd0bb",
    "content-type": "application/x-www-form-urlencoded"
  },
  "data": {
    "fname": "sarkinda"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

My angularjs request is

storeContact: function(token, data) {
            var deferred = $q.defer();
            var promise = deferred.promise;
            var settings = {
                method: "POST",
                url: "/api/api/contacts/",
                headers: {
                    'Content-Type' : 'application/x-www-form-urlencoded',
                    'Authorization': 'Bearer ' +token
                },
                data: data
            };
            console.log(settings);
            $http(settings).then(function mySuccess(response) {
                deferred.resolve(response.data);
            }, function myError(response){
                deferred.reject(response.statusText);
            });


            promise.success = function(fn) {
                promise.then(fn);
                return promise;
            };
            promise.error = function(fn) {
                promise.then(null, fn);
                return promise;
            };
            return promise;
        },

The angularJS code returns a success response and returns data from the same URL for a GET request. I believe all my Laravel code is right because POSTMAN can successfully run the call and create a new record. There must be something wrong with my angularJS code.

Note I have also tried sending data through angular js formated like this:

data: {'fname':'testname'}
2
try changing content type to application/json and try again - Shashank Jain
@Justin Please note that angularjs process ajax request in a weird way. Actually, it put all the POST data inside the body of the request. Can you try to dump the content of the body of the request for example like this : public function foo(Request $request){ var_dump($request->getContent()); die; } - erwan
I agree with @erwan - In my angular projects, I use $data = file_get_contents('php://input'); to get at the data instead of using $_POST. - swatkins
@erwan. So I put your var_dump request in my GET request, because that is the request the POST action is going to. and it returned string(0) "" - Justin
@ShashankJain, I tried changing the content type to application/json and it was still the same. - Justin

2 Answers

0
votes

Your angular code is hitting a different endpoint isnt it?

  • Angular /api/api/contacts/
  • Postman /api/contacts

Could this be the issue?

0
votes

So I don't know how to fix the $http, but I used $resource instead and it is working now:

.service('ContactsService1', function($resource) {
        return {
            contacts: function(token) {
                return $resource('/api/contacts/:contact',
        {contact: "@contact"},
        { get: {
                method: 'GET',
                headers: {
                    'Authorization' : 'Bearer ' + token
                }
            },
            delete: {
                method: 'DELETE',
                headers: {
                    'Authorization' : 'Bearer ' + token
                }
            },
            save: {
                method: 'POST',
                headers: {
                    'Content-Type' : 'application/x-www-form-urlencoded',
                    'Authorization' : 'Bearer ' + token
                },
                transformRequest: function(obj) {
                    var str = [];
                    for(var p in obj)
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                    return str.join("&");
                }
            },
        }
        )
    }}

    });

For my controller this was my code:

ContactsService1.contacts($scope.token).save(null, $scope.contact, function(data){
                $scope.result = data;
                console.log($scope.result);
                $state.go('menu.contacts', {}, {reload: true});
            }, function(data){
                if(data =='Unauthorized'){
                    window.localStorage.removeItem("token");
                    $state.go('login');
                }else{
                    //console.log(data);
                }
            });