10-1 Introduction to HTTP in AngularJS
Key Concepts
- HTTP Requests
- HTTP Responses
- AngularJS $http Service
- GET Requests
- POST Requests
- Error Handling
- Interceptors
- CORS (Cross-Origin Resource Sharing)
- Promises
- RESTful APIs
1. HTTP Requests
HTTP (HyperText Transfer Protocol) requests are messages sent by a client (such as a web browser) to a server to request data or perform an action. Common HTTP methods include GET, POST, PUT, DELETE, and more.
Example:
$http.get('/api/data') .then(function(response) { console.log(response.data); });
Imagine HTTP requests as letters sent from a client (you) to a server (a distant friend). Each letter (request) asks for something specific, like a piece of information or a task to be performed.
2. HTTP Responses
HTTP responses are messages sent by the server back to the client in response to an HTTP request. These responses contain status codes, headers, and the requested data.
Example:
$http.get('/api/data') .then(function(response) { console.log(response.data); });
Think of HTTP responses as the replies you receive from your distant friend after sending a letter. The reply (response) contains the information or action you requested.
3. AngularJS $http Service
The AngularJS $http service is a core service that facilitates communication with remote HTTP servers via the browser's XMLHttpRequest object or via JSONP.
Example:
$http({ method: 'GET', url: '/api/data' }).then(function(response) { console.log(response.data); });
Consider the $http service as a messenger who delivers your letters (requests) to the server and brings back the replies (responses).
4. GET Requests
GET requests are used to retrieve data from a specified resource. They are the most common type of HTTP request and are typically used for reading data.
Example:
$http.get('/api/data') .then(function(response) { console.log(response.data); });
Imagine GET requests as a librarian fetching a book (data) from the library (server) based on your request.
5. POST Requests
POST requests are used to send data to a server to create or update a resource. They are often used for submitting forms or uploading files.
Example:
$http.post('/api/data', {key: 'value'}) .then(function(response) { console.log(response.data); });
Think of POST requests as mailing a package (data) to a friend (server) to add something new to their collection.
6. Error Handling
Error handling in AngularJS $http service involves managing and responding to errors that occur during HTTP requests. This is crucial for providing a good user experience.
Example:
$http.get('/api/data') .then(function(response) { console.log(response.data); }) .catch(function(error) { console.error('Error:', error); });
Consider error handling as a contingency plan for when your messenger (HTTP request) encounters obstacles (errors) on the way to the server.
7. Interceptors
Interceptors in AngularJS are used to intercept and modify HTTP requests and responses globally. They are useful for tasks like adding headers, logging, and handling authentication.
Example:
app.factory('authInterceptor', function($q) { return { request: function(config) { config.headers['Authorization'] = 'Bearer ' + getToken(); return config; } }; });
Imagine interceptors as checkpoints on a road. They inspect and modify every vehicle (request/response) that passes through, ensuring they meet certain criteria.
8. CORS (Cross-Origin Resource Sharing)
CORS is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the resource originated. It is essential for secure cross-domain data transfers.
Example:
$http.get('https://api.example.com/data') .then(function(response) { console.log(response.data); });
Think of CORS as a special permission slip that allows you to borrow resources (data) from a different school (domain) during a field trip.
9. Promises
Promises in AngularJS are used to handle asynchronous operations. They provide a way to execute code after an operation completes, either successfully or with an error.
Example:
$http.get('/api/data') .then(function(response) { console.log(response.data); }) .catch(function(error) { console.error('Error:', error); });
Consider promises as a guarantee from your messenger (HTTP request) that they will deliver the reply (response) as soon as possible, with a follow-up action based on the result.
10. RESTful APIs
RESTful APIs (Representational State Transfer) are a set of architectural constraints that make web services more scalable and flexible. They use standard HTTP methods to perform CRUD (Create, Read, Update, Delete) operations.
Example:
$http.get('/api/users') // Read $http.post('/api/users', {name: 'John'}) // Create $http.put('/api/users/1', {name: 'Jane'}) // Update $http.delete('/api/users/1') // Delete
Think of RESTful APIs as a standardized set of instructions for interacting with a library (server). Each instruction (HTTP method) corresponds to a specific action (CRUD operation) on the library's resources (data).