当前位置:   article > 正文

Vue项目使用axios配置请求拦截和响应拦截以及判断请求超时处理提示_axios 请求处理

axios 请求处理

 

  哈喽大家好啊,最近做Vue项目看到axios

  axios官网:起步 | Axios 中文文档 | Axios 中文网 (axios-http.cn)​​​​​​

  重要点:

         axios是基于Promise封装的

         axios能拦截请求和响应

         axios能自动转换成json数据

        等等

安装:

$ npm install axios

  1. Vue项目中使用axios实现请求拦截

  1. import axios from 'axios';// 引入axios
  2. const httpAxios = axios.create({});// 创建实例
  3. let config = {
  4. TIMEOUT: 600000,//设置超时时间为10min
  5. };
  6. // axios 配置超时时间
  7. httpAxios.defaults.timeout = config.TIMEOUT;
  8. // axios设置 请求拦截
  9. httpAxios.interceptors.request.use(
  10. // config配置选项
  11. config => {
  12. console.log(config,'1')
  13. return config;
  14. },
  15. // error
  16. error => {
  17. return Promise.reject(error);
  18. }
  19. )
  1. Vue项目中使用axios实现响应拦截

  1. // axios响应拦截
  2. httpAxios.interceptors.response.use(
  3. // response响应成功
  4. response => {
  5. const config = response.config;
  6. console.log(config,'2')
  7. return response;
  8. },
  9. // 响应error
  10. error => {
  11. const config = error.config;
  12. console.log(config,'3')
  13. if(error.message.includes('timeout')) {
  14. return Promise.reject('timeout');// reject这个错误信息
  15. // 判断请求异常信息中是否含有超时timeout字符串
  16. }
  17. return Promise.reject('网络链接失败,请稍后再试!')
  18. }
  19. )
  1. 封装axios请求

  1. export const getHttpInfo = function (data) {
  2. return new Promise((resolve, reject) => {
  3. let token = ''
  4. if (data.headers) {
  5. token = data.headers.Authorization
  6. }
  7. httpAxios(data).then((res) => {
  8. resolve(res)
  9. }).catch((e) => {})
  10. })
  11. }
  1. 设置超时时间并在响应拦截中判断超时并提示

  1. gethttpInfo({
  2. method: 'post',
  3. url: url,
  4. data: this.order,
  5. headers: {
  6. 'Authorization': localStorage.getItem('token')
  7. }
  8. }).then((res) => {
  9. }).catch((error) => {
  10. this.$message({
  11. type: 'warning',
  12. message: error!=='timeout' ? error : '其他错误'
  13. })
  14. });

参考原文:

Vue项目请求超时处理_vue接口请求超时处理_一捆铁树枝的博客-CSDN博客

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/423030
推荐阅读
相关标签
  

闽ICP备14008679号