Axios用法示例
Axios 是一个基于 Promise 的 HTTP 客户端,可以用来发送 GET、POST 和其他类型的 HTTP 请求。这是一些基本用法示例:
首先,你需要在项目中安装 axios:
npm install axios --save
或者:
yarn add axios
然后,在文件中导入 axios 并进行使用:
import axios from 'axios';
// 发送 GET 请求
axios.get('https://api.example.com/items')
.then(response => {
// 处理成功响应
console.log(response.data);
})
.catch(error => {
// 处理错误响应
console.log(error);
});
// 发送 POST 请求
axios.post('https://api.example.com/items', {
item: 'New item'
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
以下是如何设置全局配置:
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = 'Bearer token';
也可以对单独的请求设置配置:
axios.get('/user', {
params: {
ID: 12345
},
headers: {
'Authorization' : 'Bearer token'
}
})
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
以上就是 axios 的基本用法,你可以访问其官方文档查看更多详细的信息和高级用法。