【发布时间】:2018-06-12 06:26:35
【问题描述】:
Axios 0.17.1
.then(function (response) {
console.log(response);
//console.log(response.status);
//It is an error -> SyntaxError: Unexpected token u in JSON at position 0
console.log(JSON.parse(response.data.error));
console.log(response.data.error); //undefined.
响应的console.log是
{data: "{"error":"名称必须输入多个... NULL↵
["isPipe":protected]=>↵ NULL↵ }↵}↵",状态:203,状态文本: “非权威信息”,标题:{…},配置:{…},…} 配置 :{适配器:ƒ,transformRequest:{…},transformResponse:{…},超时: 0, xsrfCookieName: "XSRF-TOKEN", ...} data : "{"error":"名称必须是 输入多个字符。"}object(Slim\Http\Response)#32 (5) {↵ [“状态”:受保护]=>↵ int(200)↵ ["reasonPhrase":protected]=>↵ 字符串(0) ""↵ ["protocolVersion":protected]=>↵ 字符串(3) "1.1"↵ ["headers":protected]=>↵ 对象(Slim\Http\Headers)#33 (1) {↵
["data":protected]=>↵ 数组(1) {↵ ["content-type"]=>↵
数组(2){↵ [“值”]=>↵ 数组(1){↵ [0]=>↵
字符串(24)“文本/html;字符集=UTF-8”↵ }↵
["originalKey"]=>↵ string(12) "Content-Type"↵ }↵ }↵ }↵ ["body":protected]=>↵ 对象(Slim\Http\Body)#31 (7) {↵
["stream":protected]=>↵ (stream)类型的资源(59)↵
[“元”:受保护]=>↵ NULL↵ [“可读”:受保护]=>↵ NULL↵
["writable":protected]=>↵ NULL↵ ["seekable":protected]=>↵
NULL↵ ["size":protected]=>↵ NULL↵ ["isPipe":protected]=>↵
NULL↵ }↵}↵" 标头:{内容类型: "application/json;charset=utf-8"} 请求:XMLHttpRequest {onreadystatechange:ƒ,readyState:4,超时:0,withCredentials: 错误,上传:XMLHttpRequestUpload,...} 状态:203 statusText: “非权威信息” 原型:对象
JSON.parse(response.data) 以及 response.data.error -> 两者都给出错误。如何读取数据?
Slimframework 3.
$data = array('error' => 'Name must be entered with more than one character.');
$newResponse = $response->withJson($data, 203);
return $newResponse;
【问题讨论】:
-
SyntaxError: 位置 0 处 JSON 中的意外标记 u
-
检查
console.log(response.data)并查看数据对象的格式。查看您的示例输出,似乎有太多引号"-data: "{"error":"Name must be entered...- this:"{"error":"看起来很奇怪 -
验证您收到的响应是否为有效的 JSON。如果有效,axios 会将其解析为 JSON 对象。否则它将返回一个纯字符串对象。
标签: javascript reactjs slim axios