What is the basic usage method of axios?
The basic usage of axios includes the following steps:
- Import the axios library: In the file where axios is needed, use the import statement to include the axios library.
- Send requests: use methods like get, post, put, delete in axios to send HTTP requests. For example, use axios.get(url) to send a GET request.
- Handling Response: Process the successful response data through the .then() method and the error message of failed requests through the .catch() method.
Here is an example code using axios to send a GET request.
import axios from 'axios';
axios.get('http://api.example.com/data')
.then(response => {
// 请求成功,处理响应数据
console.log(response.data);
})
.catch(error => {
// 请求失败,处理错误信息
console.error(error);
});
In addition to sending a GET request, you can also use axios.post(url, data) to send a POST request, axios.put(url, data) to send a PUT request, and axios.delete(url) to send a DELETE request.
When making a request, you can customize it by setting parameters such as headers and timeout. You can use the axios.defaults object to set global default configurations or specify parameters individually for each request.
The above is the basic usage of axios, which involves importing the axios library, sending requests, and handling responses to interact with the backend API.