为什么Axios请求成功但响应数据为空?
我在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组件里始终拿不到数据,这是为什么啊?
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 时设置正确的头部:
另一个是前端强制处理,比如你知道返回的是 JSON,手动 parse:
但这只是 workaround,根本解法还是让后端加 header。
顺手在浏览器里打印一下
typeof response.data,如果是 string,基本就能确认是这个问题。再检查下后端有没有加
Content-Type: application/json头部,没有的话Axios可能不认识。实在不行就用Fetch绕过Axios看看是不是它的问题。累死了,希望能帮到你。