乐闻世界logo
搜索文章和话题

How do I get the HTTP response code from a successful React query?

1个答案

1

When developing with React, retrieving HTTP response codes often depends on the data-fetching library you choose. For instance, if you're using the Fetch API or third-party libraries like Axios, the approach varies slightly. Below, I'll explain how to retrieve HTTP response codes in both scenarios.

Using Fetch API

When using the native Fetch API for data requests, you can retrieve HTTP response codes by checking the status property of the response object. Here's a simple example:

javascript
fetch('https://api.example.com/data') .then(response => { console.log('HTTP status code:', response.status); // Output HTTP status code if (response.ok) { return response.json(); } else { throw new Error('Something went wrong'); } }) .then(data => { console.log('Retrieved data:', data); }) .catch(error => { console.error('Request failed:', error); });

In this example, response.status will yield values such as 200, 404, or 500. response.ok is a boolean that evaluates to true when the status code falls within the 200–299 range, allowing you to verify if the request was successful.

Using Axios

If you're using Axios for HTTP requests, retrieving response codes is straightforward. Axios requests return a response object containing a status field. Here's an example:

javascript
axios.get('https://api.example.com/data') .then(response => { console.log('HTTP status code:', response.status); // Output HTTP status code console.log('Retrieved data:', response.data); }) .catch(error => { if (error.response) { // Request was sent, but server response status code is outside the 2xx range console.log('HTTP status code:', error.response.status); } else if (error.request) { // Request was sent, but no response was received console.log('No response received'); } else { // An issue occurred while sending the request console.log('Error', error.message); } });

With Axios, if the request is successful (i.e., HTTP status code in the 200–299 range), you can directly access the status code from response.status. If the request fails (e.g., status code is 400 or 500), the error object error.response.status contains the HTTP status code.

Summary

Whether using Fetch or Axios, retrieving HTTP response codes is relatively straightforward, as it involves accessing the status property of the response object. By doing so, you can handle various HTTP statuses, such as redirects, client errors, or server errors, and implement corresponding logic. This is crucial for developing robust web applications.

2024年8月5日 11:34 回复

你的答案