如何解决在nodejs/express中返回时如何保留文本格式?
这是 nodejs/express 后端服务器控制台输出中的文本文件,格式简洁:
abi: [
{
"inputs": [
{
"internalType": "uint256","name": "_value","type": "uint256"
},{
"internalType": "string","name": "_itemName","type": "string"
},...
]
当移动前端(React Native)接收到上述文件时,变成:
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"\n\t\t\t},\n\t\t\t{\n\t\t\t\t"internalType": "string",\n\t\t\t\t"name": "_itemName",\n\t\t\t\t"type":...]'
文本文件的格式和内容因添加了 \n
和 \t
而改变,不能用作函数调用的输入。当从 nodejs 服务器返回时,有没有办法保留或恢复原始的漂亮和整洁的格式?
更新:
文本字符串在nodejs/express服务器上以json格式返回:
return res.status(200).send({dude:_dude.deploy_address,fex:_fex.deploy_address,forsale:{abi:_forsale.abi,bytecode:_forsale.bytecode}});
这是来自移动设备的 fetch
:
let res = await fetch(beUrl,{method: "GET",headers: {
'Accept': 'application/json,text/plain','Content-Type': 'application/json',}});
let res1 = await res.json();
解决方法
保留和恢复格式的方式如下:
在 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 abi 和字节码:
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);
res3 和 res4 将文本格式恢复到原来在 nodejs/express 服务器上的格式。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。