【问题标题】:Axios - How to read JSON response?Axios - 如何读取 JSON 响应?
【发布时间】: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


【解决方案1】:

在 Axios 中响应已经作为 javascript 对象,无需解析,只需获取响应和访问数据。

【讨论】:

  • console.log(response.data.error); //undefined - 我可以记录 response.data 但 response.data.error 未定义。无法使用 JSON.parse - 它给了我错误。
  • 这意味着 response.data 存在但没有“错误”键,您可以发布 response.data 的输出吗?通常当 response.error 未定义时,仅仅意味着 axios 响应没有错误。
  • 黄色框(内容)是从 slimframework 收到的响应的 console.log。 - 请检查我是否再次更新。
  • 你能发布 RAW 输出吗? ES:console.log(响应)。如果您使用的是 chrome,我的意思不是网络中的“预览”选项卡,而是“响应”选项卡。
  • 你应该提供一个例子而不是说就做吧
【解决方案2】:

假设来自服务器的响应如下所示:

{"token": "1234567890"}

然后在 Axios 中你可以这样访问它:

console.log( response.data.token )

【讨论】:

    【解决方案3】:

    我的格式响应与控制台日志中的格式响应类似,我的问题是我的 .json 文件格式不正确。我少了一个逗号。发布您的 json 文件以查看。

    【讨论】:

      【解决方案4】:

      如前所述,Axios 已经默认返回 JSON。只需将 response.data 用作简单的 JS 对象即可。

      但是,以下见解可能对其他人有所帮助:我遇到了 Axios 将响应作为字符串返回的问题。经过调查,我发现服务器返回了一个无效的 JSON(它是一个静态文件服务器)。修复 JSON 格式后,Axios 再次使用 JSON 代替字符串。

      【讨论】:

        【解决方案5】:

        axios 通过默认将响应转换为 JSON,您必须使用 response.data 而不是 response

        export const addPosts = () => async (dispatch) => {
        await axios('https://jsonplaceholder.typicode.com/todos/1')
            .then(response => dispatch({type: postActionTypes.POSTS, payload: response.data}))}
        

        【讨论】:

          【解决方案6】:

          你可以简单地得到它,

          例如:

          {
              "terms": {
          
                  "title": "usage",
          
                  "message": "this is the usage message"
          
              }
          
          }
           
          

          当响应看起来像这样时,您可以使用 "response.data" 获取它,等等....

          .then(response => 
                  console.log( response.data.terms.message)
                  
            
          

          干杯!

          【讨论】:

            【解决方案7】:

            这里是示例代码,

            try {
              const res = await axios.get("/end-point");
              console.log("JSON data from API ==>", res.data);
            } catch (error) {
              // handle error
            }
            

            【讨论】:

              【解决方案8】:

              我遇到了类似的问题。正如其他人所指出的,axios 将 json 作为 js 对象读取,您可以轻松地在层次结构中移动以获取字段数据。

              但是,对我来说,axios 不想将 json 作为对象读取,而是返回一个字符串。原因是由于文件中先前的行删除,json末尾有一个挂逗号。所以文件内容不是有效的 json,axios 只是返回了一个字符串。 去掉逗号,一切正常。

              我建议检查 json 是否有任何不正确的语法。

              【讨论】:

                【解决方案9】:

                出于某种原因,在我的情况下,JSON 格式正确,但无论如何都以字符串形式返回。通过这个解决方法,我解决了这个问题。

                // ...
                return await this.axios_instance.request<T>({
                    method,
                    url,
                    headers,
                    params,
                    transformResponse: (data) => JSON.parse(data), // <----------
                    data,
                });
                

                简单地说,我明确要求使用 JSON.parse 转换响应。出于某种原因,这行得通,而其他答案却没有。

                这对我有用!希望对您有所帮助。

                【讨论】:

                  【解决方案10】:

                  所以我发现这篇文章是为了寻找我的问题的答案。 “如何访问 api 返回的 json 文件中的数据。”尽管如此,最终对我有用的是对stackoverflow上一个类似问题的回答,该问题的链接是Axios. How to get error response even when api return 404 error, in try catch finally

                  但是,这是我用来访问后端 api 返回的错误代码的代码。 axios.get(/sanctum/csrf-cookie).then(响应 => { axios.post(api/register, registerInfo) .then(响应 => { console.log('这是响应:' + response.data.errors); }).catch(错误 => { console.log('这是错误:' + error.response.data.errors.name); }); });

                  【讨论】:

                  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 2018-09-24
                  • 2013-03-11
                  • 2021-01-28
                  • 2013-05-05
                  • 2019-03-19
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多