AngularJS : HTTP Request GET and POST with sample code

In AngularJS we can able to sent HTTP request to external servers with help of $http. It will support both POST and GET methods request from Angular. In this we specify method and request url as JSON format in function callback.

Syntax:

$http({
  method: METHOD,
  url: CALL_BACK_URL
}).then(function successCallback(response) {
  // Success Callback response
}, function errorCallback(response) {
  // Error Callback response
});

Example:

// GET Method.
$scope.getUserList = function() {
$http({
  method: 'GET',
  url: 'http://192.168.99.69:8081/api/users',
  headers: {
    'Content-Type': undefined
  }
}).then(function successCallback(response) {
    console.log(response.data);
  }, function errorCallback(response) {
    console.log(response);
  });
};
 
// POST Method.
$scope.getUserList = function() {
$http({
  method: 'POST',
  url: 'http://192.168.99.69:8081/api/users',
  headers: {
    'Content-Type': undefined
  }
  data: { name: 'codeexprtz' }
}).then(function successCallback(response) {
    console.log(response.data);
  }, function errorCallback(response) {
    console.log(response);
  });
};

 

Category: