Tính năng
- Tạo request từ trình duyệt bằng XMLHttpRequest
- Tạo request từ node.js bằng http
- Hỗ trợ Promise API
- Đón chặn request và response
- Biến đổi dữ liệu request và response
- Bãi bỏ request
- Tự động chuyển đổi cho dữ liệu JSON
- Hỗ trợ phía client bảo vệ chống lại XSRF
Cài đặt
- Sử dụng npm: $ npm install axios
- Sử dụng yarn: $ yarn add axios
Ví dụ
importaxios from 'axios';
// Tạo một request để truy xuất người dùng ứng với ID cho sẵn:
axios.get('/user?ID=12345')
.then(function(response){
// xử trí khi thành công
console.log(response);
})
.catch(function(error){
// xử trí khi bị lỗi
console.log(error);
})
.then(function(){
// luôn luôn được thực thi
});
// Cái request bên trên cũng có thể được làm bằng cách sau, tùy
ý
axios.get('/user',{
params:{
ID:12345
}
})
.then(function(response){
console.log(response);
})
.catch(function(error){
console.log(error);
})
.then(function(){
// luôn luôn được thực thi
});
// Nếu muốn sử dụng async/await thì viết như sau
asyncfunctiongetUser(){
try{
const response =await axios.get('/user?ID=12345');
console.log(response);
}catch(error){
console.error(error);
}}