Debugging $http
calls in AngularJS is essential to troubleshoot API issues, track network requests, and optimize performance. Chrome DevTools provides a powerful set of tools to inspect and debug HTTP requests.
1. Opening Chrome DevTools
To access DevTools:
- Open Google Chrome.
- Right-click anywhere on the page and select Inspect.
- Navigate to the Network tab.
- Filter requests by XHR/Fetch to see API calls.
2. Inspecting $http
Requests
When an API call is made using $http
, it appears in the Network tab:
- Look for the request URL in the Name column.
- Click on the request to view details.
Key Sections in Network Tab
- Headers → Shows request headers, status code, and API endpoint.
- Payload → Displays data sent in a POST request.
- Response → Shows the API’s response.
- Timing → Measures request duration.
3. Checking Console for Errors
If an API call fails:
- Open Console (Ctrl + Shift + J or Cmd + Option + J on Mac).
- Look for red error messages.
- Common errors:
- 404 (Not Found) → API endpoint incorrect.
- 500 (Internal Server Error) → Server issue.
- 401 (Unauthorized) → Authentication required.
- CORS Policy Error → Server doesn’t allow cross-origin requests.
To log API errors in AngularJS:
$http.get("https://api.example.com/data")
.then(function(response) {
console.log("Success:", response.data);
})
.catch(function(error) {
console.error("Error:", error);
});
4. Using console.log
for Debugging
To check API response in AngularJS:
$http.get("https://api.example.com/data")
.then(function(response) {
console.log("Response Data:", response.data);
})
.catch(function(error) {
console.error("API Call Failed:", error);
});
- Open Console to view
console.log
outputs. - This helps verify if the API is returning correct data.
5. Using Breakpoints in DevTools
To debug AngularJS $http
requests:
- Open Sources tab in DevTools.
- Locate the AngularJS file making the request.
- Click on the line number to set a breakpoint.
- Refresh the page and inspect variable values.
6. Retrying Failed API Requests
If an API request fails, retry it manually:
- Go to Network tab.
- Right-click the failed request → Replay XHR.
- Inspect the response for debugging.
7. Monitoring API Performance
- Open Network tab → Click on an API call.
- Go to Timing to check:
- DNS Lookup Time
- Request Sent
- Server Response Time
- Total Load Time
8. Using Postman for API Testing
If $http
requests fail in AngularJS, test them separately using Postman:
- Copy API endpoint.
- Select GET/POST method.
- Add required headers (
Authorization
,Content-Type
). - Check the response.
9. Handling API Errors Gracefully
Use .catch()
to manage API failures:
$http.get("https://api.example.com/data")
.then(function(response) {
console.log("Data received:", response.data);
})
.catch(function(error) {
if (error.status === 404) {
console.error("Data not found!");
} else if (error.status === 500) {
console.error("Server error! Try again later.");
}
});