【问题标题】:Getting JSON from a REST endpoint with axios - ReactJS使用 axios 从 REST 端点获取 JSON - ReactJS
【发布时间】:2021-02-24 23:03:36
【问题描述】:

我正在尝试从我的 react 应用程序的端点解析一个 json 列表。但是 json 被识别为字符串,当我使用扩展运算符时,结果是扩展每个字符。从服务器端,我从数据库接收到 json,我只是使用 json.dumps() 到端点。有趣的事实是,它已经工作了很长时间,但我不知道为什么现在失败了。我尝试使用JSON.parse(),但收到的对象是无效输入,然后我也转向服务器,但是当我读取响应(python)时,在转储它之前,它作为字典列表完全可读(我也试过jsonify(),将列表添加到字典等中。)。如果我只发送了一个对象json.dumps(list[0]),则可以将 dict 视为反应端的对象。

端点数据:

[{"n": {"altitude": [110, 110], "subtype": "", "name": "Alqueva", "location": [-7.49623775, 38.19746677, 110.0], "fwl": 152, "block": "", "id": "0", "tag": "origin", "power": 520, "type": "Barragem", "tia": 0}}, {"n": {"altitude": [0, 0], "subtype": "", "name": "Alamos", "block": "", "location": [0.0, 0.0, 0.0], "fwl": 227.5, "id": "1", "tag": "distribution", "power": 0, "type": "Barragem", "tia": 0}}, {"n": {"altitude": [0, 0], "subtype": "", "name": "Loureiro", "location": [0.0, 0.0, 0.0], "fwl": 220, "block": "", "id": "2", "tag": "distribution", "power": 0, "type": "Barragem", "tia": 0}}, ...

javascript/react 代码:

loadNeo4jAPI = async () => {
    await axios.get("http://192.xxx.xx.xxx:5001/api/waternode").then((res) => {
      const { data } = res;
      this.setState({ waternodes: [...data] });
      console.log("nodes", this.state.waternodes);
    });
    this.forceUpdate();
  };

结果:


App.js:43 nodes 
(111214) ["[", "{", """, "n", """, ":", " ", "{", """, "a", "l", "t", "i", "t", "u", "d", "e", """, ":", " ", "[", "1", "1", "0", ",", " ", "1", "1", "0", "]", ",", " ", """, "s", "u", "b", "t", "y", "p", "e", """, ":", " ", """, """, ",", " ", """, "n", "a", "m", "e", """, ":", " ", """, "A", "l", "q", "u", "e", "v", "a", """, ",", " ", """, "l", "o", "c", "a", "t", "i", "o", "n", """, ":", " ", "[", "-", "7", ".", "4", "9", "6", "2", "3", "7", "7", "5", ",", " ", "3", "8", ".", "1", "9", "7", "4", "6", …]

有证据证明 axios 接收到的内容类型为 json:

【问题讨论】:

  • 在数据之前使用 JSON.parse 或者检查你的 api 为什么它返回字符串而不是 json 数组。 { waternodes: [...JSON.parse (data)] }
  • @Eric,正如我在文中所说,JSON.parse(data) 失败:Uncaught (in promise) SyntaxError: Unexpected token N in JSON at position 27570 。但我现在使用了一个 json linter (jsonlint.com),问题可能出在 NaN 值上。我会测试
  • 确保您的后端 api 返回一个有效的 json。 github.com/axios/axios/issues/1723

标签: javascript python json reactjs axios


【解决方案1】:

[解决方案] JSON 文件包含 NaN 值,由于它不是字符串,因此 json 无效。我发现使用 json linter 的在线版本。还要感谢@Eric

【讨论】:

    猜你喜欢
    • 2019-05-15
    • 2021-02-07
    • 2023-02-01
    • 2018-10-10
    • 2022-06-12
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 2018-09-22
    相关资源
    最近更新 更多