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

How to get raw response data from axios request?

1个答案

1

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:

javascript
import 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. The response object contains complete response details, such as status code (status), status message (statusText), and response headers (headers), etc.
  • response.data is 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 回复

你的答案