【问题标题】:How to fix text data format fetched from backend server?如何修复从后端服务器获取的文本数据格式?
【发布时间】:2021-01-21 21:59:56
【问题描述】:

我的 React Native (0.62.3) 应用程序 fetch 来自 nodejs 12.x 后端服务器的文本数据。这是出现在后端服务器上的abi

 abi: [
        {
                "inputs": [
                        {
                                "internalType": "uint256",
                                "name": "_value",
                                "type": "uint256"
                        },
                        {
                                "internalType": "string",
                                "name": "_itemName",
                                "type": "string"
                        },
...
]

文本在后端 nodejs 服务器上返回:

return res.status(200).send({dude:_dude.deploy_address, fex:_fex.deploy_address, forsale:{abi:_forsale.abi, bytecode:_forsale.bytecode}});

这里是获取和解析接收到的数据的 RN 代码:

  let res = await fetch(beUrl, {method: "GET"});
  let res1 = await res.json();

res1 控制台输出的数据格式与abi 相当密集,这是一个长文本数组:

abi: '[\n\t{\n\t\t"inputs": [\n\t\t\t{\n\t\t\t\t"internalType": "uint256",\n\t\t\t\t"name": "_value",\n\t\t\t\t"type": "uint256"\....]'

试过encodeURI(abi),但没有帮助。如何修复获取到的数据在RN上的格式?

【问题讨论】:

  • 尝试将其解析为 await res.text()
  • res.text() 抛出错误。

标签: node.js react-native fetch


【解决方案1】:

以下是保留和恢复格式的方式:

在 nodejs/express 服务器上,JSON.stringift 整个返回对象:

 let obj = JSON.stringify({dude:_dude.deploy_address, fex:_fex.deploy_address, forsale:{abi:(_forsale.abi), bytecode:(_forsale.bytecode)}});
    return res.status(200).send(obj);

在前端,JSON.parse abibytecode

let res = await fetch(beUrl, {method: "GET", headers: {
                                                'Accept': 'application/json, text/plain',
                                                'Content-Type': 'application/json',   
                                              }});
      let res1 = await res.json();
      let res3 = JSON.parse(res1.forsale.abi);
      let res4 = JSON.parse(res1.forsale.bytecode);

res3res4 将文本格式恢复到它在 nodejs/express 服务器上的原始格式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 2014-12-19
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多