When using axios for network requests, it returns a response object containing multiple fields. To retrieve the raw response data, focus on the data field within the response object, which contains the actual data returned by the server.
For example, suppose we use axios to make a GET request to an API to retrieve user information. Here are the steps to write code and extract data from the response:
javascriptimport axios from 'axios'; axios.get('https://api.example.com/users/1') .then(response => { // response is a complete response object console.log('Complete response object:', response); // Retrieve raw data const rawData = response.data; console.log('Raw response data:', rawData); }) .catch(error => { console.error('Request failed:', error); });
In this example:
axios.get('https://api.example.com/users/1')initiates a GET request..then(response => {...})is the callback function for handling successful responses. Theresponseobject contains complete response details, such as status code (status), status message (statusText), and response headers (headers), etc.response.datais the raw data returned by the server, which is typically in JSON format but could be a string, Blob, or other formats depending on the server's response.
Additionally, if you need to view or use the complete response headers or status code for debugging, you can directly access response.headers or response.status.
By doing this, you can effectively extract the data or information you need from the axios response.
2024年8月9日 01:34 回复