使用get函数[Express]从Solidity结构接收JSON

时间:2019-05-20 10:43:00

标签: node.js angular express solidity web3js

我需要这样的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);

});

并保持稳定:

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?

谢谢您的回答。

1 个答案:

答案 0 :(得分:0)

您应该在节点服务器中返回json格式

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

由于这一行,您还会收到阵列响应

dati.push(newDati);