Angularjs $http post error in Ionic


#1

Here is my controller. When I want to post some data to backend, I get error.

.controller('LoginCtrl', function($http, $scope, $state, $ionicPopup, AuthService) {
  $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
  $http({
      method: 'POST',
      url: 'http://cms.focusweb.ir/Json/get_article',
      data: { id: 25 },
      headers: {'Content-Type': 'application/x-www-form-urlencoded'}
  })
  .success(function(response) {
      // handle success things
      console.log(response);
  })
  .error(function(data, status, headers, config) {
      // handle error things
  })
})

The error I get :

Error: Unexpected request: POST http://cms.focusweb.ir/Json/get_article
No more request expected
at $httpBackend (angular-mocks.js:1207)
at sendReq (ionic.bundle.js:19160)
at status.$get.serverRequest (ionic.bundle.js:18872)
at processQueue (ionic.bundle.js:23394)
at ionic.bundle.js:23410
at Scope.parent.$get.Scope.$eval (ionic.bundle.js:24673)
at Scope.parent.$get.Scope.$digest (ionic.bundle.js:24484)
at Scope.parent.$get.Scope.$apply (ionic.bundle.js:24778)
at done (ionic.bundle.js:19191)
at completeRequest (ionic.bundle.js:19363)

#2

When posting using url-form-encoded you need to pass the data in a string rather than a JSON object

controller(‘LoginCtrl’, function($http, $scope, $state, $ionicPopup, AuthService) {
$http.defaults.headers.post[‘Content-Type’] = ‘application/x-www-form-urlencoded;charset=utf-8’;
$http({
method: ‘POST’,
url: ‘http://cms.focusweb.ir/Json/get_article’,
data: “id=25&otherparam=43”,
headers: {‘Content-Type’: ‘application/x-www-form-urlencoded’}
})
.success(function(response) {
// handle success things
console.log(response);
})
.error(function(data, status, headers, config) {
// handle error things
})
})

HTH :grin:


#3

@webslinger Thanks, but again the same error.


#4

I think the error is API end :smile:

http://codepen.io/webslinger/pen/LppQYx

For this to run on a browser you’ll need to run chrome with --disable-web-security flag

A PHP Error was encountered

Severity: Notice
Message: Trying to get property of non-object
Filename: controllers/Json.php
Line Number: 20

[]


#5

Finally I found the problem.
The problem is with ngMockE2E AngularJS module that should be used only for tests and not included like dependency for you project.

So solution: just removing this dependancy!

Thank you for your attention @webslinger


#6

I’m using ngMockE2E for ‘backendless’ development, so excluding the module (and thus mocked service) is not an option for me. I don’t know if just removing the dependency is a proper solution because backendless development is a common approach.

edit:
Adding proxy settings to your ionic.config.json (previously ‘ionic.project’) seems to fix it. You can then use your ngMockE2E modules as expected.

  "proxies": [
    {
      "path": "/rest",
      "proxyUrl": "https://your-domain/rest"
    }
  ]