vue实现axio请求
安装 Axios
在 Vue 项目中安装 Axios,可以通过 npm 或 yarn 完成:
npm install axios
yarn add axios
引入 Axios
在需要发送请求的组件或全局配置中引入 Axios:
import axios from 'axios';
全局配置 Axios
可以在 main.js 或入口文件中全局配置 Axios,例如设置默认的请求头或基地址:
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = 'Bearer token';
发送 GET 请求
使用 Axios 发送 GET 请求获取数据:
axios.get('/users')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
发送 POST 请求
发送 POST 请求提交数据:

axios.post('/users', { name: 'John', age: 30 })
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
发送 PUT 请求
更新数据可以使用 PUT 请求:
axios.put('/users/1', { name: 'John', age: 31 })
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
发送 DELETE 请求
删除数据可以使用 DELETE 请求:
axios.delete('/users/1')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
拦截请求和响应
Axios 支持拦截器,可以在请求或响应被处理前进行拦截:

axios.interceptors.request.use(config => {
console.log('Request sent:', config);
return config;
}, error => {
return Promise.reject(error);
});
axios.interceptors.response.use(response => {
console.log('Response received:', response);
return response;
}, error => {
return Promise.reject(error);
});
使用 async/await
结合 async/await 可以更简洁地处理异步请求:
async function fetchUsers() {
try {
const response = await axios.get('/users');
console.log(response.data);
} catch (error) {
console.error(error);
}
}
错误处理
统一处理请求错误:
axios.get('/users')
.then(response => {
console.log(response.data);
})
.catch(error => {
if (error.response) {
console.error('Server responded with error:', error.response.status);
} else if (error.request) {
console.error('No response received:', error.request);
} else {
console.error('Request setup error:', error.message);
}
});
取消请求
使用 CancelToken 可以取消未完成的请求:
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/users', {
cancelToken: source.token
})
.then(response => {
console.log(response.data);
})
.catch(thrown => {
if (axios.isCancel(thrown)) {
console.log('Request canceled:', thrown.message);
} else {
console.error(thrown);
}
});
// 取消请求
source.cancel('Operation canceled by the user.');






