Axios 0.17.1读取JSON响应报错,如何正确获取数据?
问题分析
从你描述的情况来看,console.log(response)显示response.data里既有正确的JSON字符串,又附带了Slim\Http\Response对象的输出,这说明后端返回的响应体不是纯净的JSON——额外的输出内容和JSON混在一起,导致Axios无法正确自动解析,手动JSON.parse也会因为字符串格式错误报错,直接访问response.data.error自然会得到undefined。
这种情况通常是Slim后端代码里不小心输出了额外内容导致的,比如在return $newResponse之前,有echo、var_dump或者print_r这类打印语句(比如不小心打印了$response对象),这些内容会被追加到JSON响应的后面,破坏了响应体的纯净性。
解决方案
1. 清理后端的额外输出
检查你的Slim代码,确保在返回$newResponse之前,没有任何额外的输出语句。比如要删除这类错误代码:
// 错误示例:return之前有额外打印 var_dump($response); // 这行会输出Slim\Response对象,破坏响应体 $data = array('error' => 'Name must be entered with more than one character.'); $newResponse = $response->withJson($data, 203); return $newResponse;
只保留生成并返回JSON响应的核心代码即可。
2. 确保响应头正确设置(可选,但推荐)
虽然Slim的withJson方法会自动设置Content-Type: application/json响应头,但可以手动显式设置来确保正确性:
$data = array('error' => 'Name must be entered with more than one character.'); $newResponse = $response->withJson($data, 203) ->withHeader('Content-Type', 'application/json'); return $newResponse;
3. 前端正确读取数据
当后端返回纯净的JSON响应后,Axios 0.17.1会自动解析JSON为JavaScript对象,你不需要手动调用JSON.parse,直接访问response.data.error即可:
axios.get('/your-api-endpoint') .then(function (response) { console.log(response.data.error); // 会正确输出"Name must be entered with more than one character." }) .catch(function (error) { console.error(error); });
验证方法
可以先通过Postman或者curl直接请求后端接口,查看响应体是否是纯净的JSON字符串。如果响应体里只有{"error":"Name must be entered with more than one character."},没有其他额外内容,那前端Axios就能正常解析了。
内容的提问来源于stack exchange,提问作者Mahesh

