node.js - 使用 get 函数从 Solidity 结构接收 JSON [Express]

标签 node.js angular ecmascript-6 rxjs single-page-application

我需要这样的 JSON:

{meteo: 'Fluorine', commento: 'F'}

但是当我使用 get 函数时,我收到以下消息:

[ '1meteo', '1commento', meteo: '1meteo', commento: '1commento' ]

我使用 Express 作为后端,这是我的代码:

app.get('/getallgiornale', async function (req, res) {

  // Get the contract instance.
  const networkId = await web3.eth.net.getId();
  const deployedNetwork = Giornaledeilavori.networks[networkId];
  const instance = new web3.eth.Contract( Giornaledeilavori.abi, deployedNetwork && deployedNetwork.address );

  // getAll
  const response = await instance.methods.getAll().call();
  res.send(response);

});

在 Solidity 中:

contract Giornaledeilavori {
struct Dati{
string meteo;
string commento;
}
Dati[] public dati;

//getAll function:
function getAll() public returns (Dati[] memory){
  Dati[] memory d = dati;
  return d;
}

//set function:
  function setDato(string memory _meteo, string memory _commento) public  {
    Dati memory newDati = Dati({
    meteo: _meteo,
    commento: _commento
  });
    dati.push(newDati);
}

Express中的set函数是这样的:


app.get('/setgiornale', async function (req, res) {
  var accounts = await web3.eth.getAccounts();
  // Get the contract instance.
  const networkId = await web3.eth.net.getId();
  const deployedNetwork = Giornaledeilavori.networks[networkId];
  const instance = new web3.eth.Contract( Giornaledeilavori.abi, deployedNetwork && deployedNetwork.address );

  // setDati
  instance.methods.setDato('1meteo','1commento').send({
    from: accounts[0],
    gas:"4500000",
    privateFor:['ROAZBWtSacxXQrOe3FGAqJDyJjFePR5ce4TSIzmJ0Bc=']
  },(error, transactionHash) => {
    if(error) {
      console.log(error);
      res.send(500);
    } else {
      res.send(transactionHash);
    }
  });
})

在set函数中,我尝试使用json而不是send,但它不起作用。 我使用了 json stringify 但它不起作用。

如何接收 json?

感谢您的解答。

最佳答案

您应该在 Node 服务器中返回 json 格式:

return res.json({ questions: questions });

由于这一行,您还收到了数组响应

dati.push(newDati);

关于node.js - 使用 get 函数从 Solidity 结构接收 JSON [Express],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56219258/

相关文章:

node.js - 我应该如何从 AWS Lambda 函数连接到 Redis 实例?

angular - Ionic 4 native 插件地理定位给我 "Module not found: Error: Can' t 解析 'rxjs/Observable'"

angular - 在构造函数中服务初始化期间是否需要使用 'readonly' 关键字?

javascript - Draftjs: TypeError: TypeError: this.getImmutable(...) 未定义

javascript - ES6 在当前 Promise 完成后无法返回新的 Promise

javascript - 对于函数范围的变量,用 const 代替 var?

node.js - Docker是否具有日志状态,例如错误,警告,信息?

javascript - 如何从数组中获取上一个和下一个 id

javascript - 如何在 Node js 中使用请求包禁用多个 http(s) 请求?

javascript - Angular2 - 登录后重定向