在JavaScript中,Axios调用总是以then()回调结束,这是因为Axios返回的是一个Promise对象。以下是一个使用Axios进行API调用的示例:
import axios from 'axios';
// 发起GET请求
axios.get('https://api.example.com/data')
.then(response => {
// 处理成功的响应
console.log(response.data);
})
.catch(error => {
// 处理错误
console.error(error);
});
// 发起POST请求
axios.post('https://api.example.com/data', { name: 'John Doe' })
.then(response => {
// 处理成功的响应
console.log(response.data);
})
.catch(error => {
// 处理错误
console.error(error);
});
在上面的代码中,我们使用Axios的get()和post()方法进行GET和POST请求。然后,我们使用then()回调处理成功的响应,并使用catch()回调处理错误。
请注意,Axios还提供了其他方法(如put()、delete()等)来发送不同类型的请求。无论你使用哪种方法,调用总是以then()回调结束。
下一篇:axios多部分请求失败