Sending GET and POST requests with $http

Loading

The $http service in AngularJS is used to communicate with a server using AJAX (Asynchronous JavaScript and XML) requests. It allows sending and receiving data from REST APIs using HTTP methods like GET and POST.


1. What is $http?

$http is a built-in AngularJS service that enables making HTTP requests to fetch or send data to a remote server. It returns a promise, which can be handled using .then() or .catch().

Basic Syntax of $http

$http({
method: 'METHOD_TYPE',
url: 'API_ENDPOINT',
data: { /* Data for POST/PUT requests */ }
}).then(function(response) {
// Success callback
}, function(error) {
// Error callback
});

2. Making a GET Request with $http

The GET method is used to fetch data from a server.

Example: Fetching Data from an API

var app = angular.module("myApp", []);

app.controller("MyController", function($scope, $http) {
$http.get("https://jsonplaceholder.typicode.com/posts")
.then(function(response) {
$scope.posts = response.data; // Assigning API response to the scope variable
})
.catch(function(error) {
console.error("Error fetching data:", error);
});
});

Explanation:

  • $http.get("API_URL") makes a GET request.
  • .then(function(response) {...}) handles the successful response.
  • .catch(function(error) {...}) catches and logs any errors.

Use Case: Fetching user data, product lists, or any read-only information.


3. Making a POST Request with $http

The POST method is used to send data to a server, such as submitting a form.

Example: Sending Data to an API

var app = angular.module("myApp", []);

app.controller("MyController", function($scope, $http) {
$scope.newPost = { title: "AngularJS", body: "Learning AngularJS" };

$scope.addPost = function() {
$http.post("https://jsonplaceholder.typicode.com/posts", $scope.newPost)
.then(function(response) {
console.log("Post added:", response.data);
})
.catch(function(error) {
console.error("Error posting data:", error);
});
};
});

Explanation:

  • $scope.newPost contains the data to be sent.
  • $http.post("API_URL", data) makes a POST request with data.
  • .then(function(response) {...}) handles success.
  • .catch(function(error) {...}) handles errors.

Use Case: Submitting user forms, creating new records in a database.


4. Handling Errors in $http Requests

It is always recommended to handle errors properly in HTTP requests.

Example: Handling Errors in GET and POST

app.controller("MyController", function($scope, $http) {
$http.get("https://jsonplaceholder.typicode.com/posts")
.then(function(response) {
$scope.posts = response.data;
})
.catch(function(error) {
console.error("Error fetching data:", error.status, error.statusText);
});

$scope.addPost = function() {
$http.post("https://jsonplaceholder.typicode.com/posts", $scope.newPost)
.then(function(response) {
console.log("Post added:", response.data);
})
.catch(function(error) {
console.error("Error posting data:", error.status, error.statusText);
});
};
});

🔹 Common HTTP Errors:

  • 400 – Bad Request
  • 401 – Unauthorized
  • 404 – Not Found
  • 500 – Server Error

5. Setting Headers in $http Requests

Sometimes, we need to pass custom headers, such as an authentication token.

Example: Setting Authorization Headers

$http({
method: 'GET',
url: 'https://api.example.com/data',
headers: {
'Authorization': 'Bearer your_token_here',
'Content-Type': 'application/json'
}
}).then(function(response) {
console.log("Data received:", response.data);
});

Use Case: Secure API calls requiring authentication.


6. Combining GET and POST in One Controller

Example: Fetching and Adding Posts in One Controller

var app = angular.module("myApp", []);

app.controller("PostController", function($scope, $http) {
// Fetch posts
$http.get("https://jsonplaceholder.typicode.com/posts")
.then(function(response) {
$scope.posts = response.data;
})
.catch(function(error) {
console.error("Error fetching posts:", error);
});

// Add a new post
$scope.newPost = { title: "", body: "" };

$scope.addPost = function() {
$http.post("https://jsonplaceholder.typicode.com/posts", $scope.newPost)
.then(function(response) {
$scope.posts.push(response.data); // Add new post to the list
$scope.newPost = {}; // Reset form
})
.catch(function(error) {
console.error("Error posting data:", error);
});
};
});

Use Case: Fetching a list of blog posts and adding new ones dynamically.

Leave a Reply

Your email address will not be published. Required fields are marked *