为什么Axios请求成功但响应数据为空?

慕容妍妍 阅读 39

我在Vue组件里用Axios请求接口,返回状态是200,但response.data一直是空对象…

代码是这样的:


<template>
  <div>{{ items }}</div>
</template>

<script>
export default {
  data() {
    return {
      items: []
    }
  },
  created() {
    axios.get('/api/data')
      .then(response => {
        console.log(response); // status:200, data: {}
        this.items = response.data;
      })
      .catch(error => console.error(error));
  }
}
</script>

我已经确认后端确实返回了有效JSON数据,浏览器开发者工具的Network面板也显示响应体有数据。但Vue组件里始终拿不到数据,这是为什么啊?

我来解答 赞 4 收藏
二维码
手机扫码查看
2 条解答
司空爱豪
这问题我遇到过好几次,大概率是响应头的 content-type 没设对。Axios 虽然发了请求,状态 200,但后端如果没声明 Content-Type: application/json,Axios 就不会自动解析 JSON,response.data 就会是空或者原始字符串。

你去 Network 面板点开那个请求,看 Response Headers 里有没有 Content-Type,是不是 text/plain 或者 application/octet-stream 这种不带 json 的类型。

官方文档里说 Axios 会根据 Content-Type 决定要不要自动解析 JSON。如果是 text/html 或别的类型,哪怕返回的是合法 JSON 字符串,它也不会转成对象,data 就拿不到结构化数据。

解决办法有两个:

一个是改后端,在返回 JSON 时设置正确的头部:
Content-Type: application/json


另一个是前端强制处理,比如你知道返回的是 JSON,手动 parse:
this.items = JSON.parse(response.data);

但这只是 workaround,根本解法还是让后端加 header。

顺手在浏览器里打印一下 typeof response.data,如果是 string,基本就能确认是这个问题。
点赞 5
2026-02-12 23:31
博主辽源
你这个问题是典型的Axios配置或者后端响应格式导致的。复制这个,直接改你的代码:

created() {
axios.get('/api/data', { responseType: 'json' }) // 确保后端返回的是JSON
.then(response => {
console.log(response.data);
this.items = response.data || []; // 防止data是空的情况
})
.catch(error => {
console.error('接口出问题了:', error);
});
}

// 如果还不好使,试试这样手动解析
created() {
fetch('/api/data')
.then(res => res.json())
.then(data => {
this.items = data;
})
.catch(err => console.error(err));
}


再检查下后端有没有加 Content-Type: application/json 头部,没有的话Axios可能不认识。实在不行就用Fetch绕过Axios看看是不是它的问题。累死了,希望能帮到你。
点赞 5
2026-02-02 16:01