现象

昨天写vue的时候,使用await axios 竟然返回了undefined?

//1.组件挂载就开始请求后端api
const res = await getCourseListAPI()
  
//2.getCourseListAPI()方法
export async function getCourseListAPI() { 
    const res=await http.post('/get_course_list', {
    })
    return  res
  }
  
  
//3.http封装
import axios from 'axios';

export const baseURL = 'http://localhost';

// 创建axios实例
const http = axios.create({
  baseURL: baseURL,
  timeout: 5000
});


// axios响应拦截器
http.interceptors.response.use(
  response => {
    return response.data;
  },
  error => {
    console.log(error.response.status);
    if (error.response.status === 401) {
      ElMessage({
        message: '未登录,请先登录',
        type: 'error',
      })
      setTimeout(() => {
              // 未授权,跳转到登录页面
      // window.location.href = '/login';
      }, 1500);

    }
    return Promise.reject(error);
  }
);

追溯起源

  1. 首先是res为undefined

  2. 追踪到getCourseListAPI()内部,发现内容的res也是undefined

  3. 但在f12的控制台的网络面板中发现数据是成功的获取到了的,说明数据在中间丢失了

  4. axios的请求是,先由axios实例发出,请求拦截器拦截,响应拦截器拦截,返回到axios实例

  5. 深入到响应拦截器中,逐个探查

    response => {
      return response.data;
    },

    在这里,发现response.data不是一个响应对象,response才是正确的响应对象,响应拦截器将一个非响应对象返回给axios实例,await解析出来就是undefined

解决方案

将 return response.data 修改为 return response即可