未经拒绝的拒绝(TypeError):无法读取未定义的属性(Reading' hash')

发布于 2025-02-04 21:00:27 字数 5184 浏览 4 评论 0原文

我正在尝试制定一个解决方案,将文件存储在IPFS中,然后将哈希放在区块链上。 但是,当我尝试将文件上传到IPFS时,错误消息

“ nofollow noreferrer”> nofford noreferrer“ client

我正在使用React,Ganache,node.js,ipfs-http- 这是我的app.js代码,

import React, {Component} from 'react'
import SimpleStorageContract from '../src/SimpleStorage.json'
import getWeb3 from './utils/getWeb3'
import './css/oswald.css'
import './css/open-sans.css'
import './css/pure-min.css'
import './App.css'
const ipfsAPI = require('ipfs-http-client');
const ipfs = ipfsAPI.create({host: 'localhost', port: '5001', protocol: 'http'});
const contract = require('truffle-contract')
const simpleStorage = contract(SimpleStorageContract)
let account;
// Declaring this for later so we can chain functions on SimpleStorage.
let contractInstance;
let saveImageOnIpfs = (reader) => {
  return new Promise(function(resolve, reject) {
    const buffer = Buffer.from(reader.result);
    ipfs.add(buffer).then((response) => {
      console.log(response)
      resolve(response[0].hash);
    }).catch((err) => {
      console.error(err)
      reject(err);
    })
  })
}


class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      blockChainHash: null,
      web3: null,
      address: null,
      imgHash: null,
      isWriteSuccess: false
    }
  }
  componentWillMount() {
    ipfs.swarm.peers(function(err, res) {
      if (err) {
        console.error(err);
      } else {
        // var numPeers = res.Peers === null ? 0 : res.Peers.length;
        // console.log("IPFS - connected to " + numPeers + " peers");
        console.log(res);
      }
    });
    getWeb3.then(results => {
      this.setState({web3: results.web3})
      // Instantiate contract once web3 provided.
      this.instantiateContract()
    }).catch(() => {
      console.log('Error finding web3.')
    })
  }
  instantiateContract = () => {
    simpleStorage.setProvider(this.state.web3.currentProvider);
    this.state.web3.eth.getAccounts((error, accounts) => {
      account = accounts[0];
      simpleStorage.at('0xe7D98C99d71438A072B020138dD75347792FA214').then((contract) => {
        console.log(contract.address);
        contractInstance = contract;
        this.setState({address: contractInstance.address});
        return;
      });
    })
  }
  render() {
    return (<div className="App">
      {
        this.state.address
          ? <h1>CONNECT THE CONTRACT ADDRESS:{this.state.address}</h1>
          : <div/>
      }
      <h2>UPLOAD TO IPFS:</h2>
      <div>
        <label id="file">CLICK TO UPLOAD THE FILE</label>
        <input type="file" ref="file" id="file" name="file" multiple="multiple"/>
      </div>
      <div>
        <button onClick={() => {
            var file = this.refs.file.files[0];
            var reader = new FileReader();
            // reader.readAsDataURL(file);
            reader.readAsArrayBuffer(file)
            reader.onloadend = function(e) {
              console.log(reader);
              saveImageOnIpfs(reader).then((hash) => {
                console.log(hash);
                this.setState({imgHash: hash})
              });
            }.bind(this);
          }}>UPLOAD TO IPFS AND RETURN THE HASH</button>
      </div>
      {
        this.state.imgHash
          ? <div>
              <h2>imgHash:{this.state.imgHash}</h2>
              <button onClick={() => {
                  contractInstance.set(this.state.imgHash, {from: account}).then(() => {
                    console.log('HASH HAS BEEN WRITE ON BLOCKCHAIN');
                    this.setState({isWriteSuccess: true});
                  })
                }}>PUT HASH ON BLOCKCHAIN:contractInstance.set(imgHash)</button>
            </div>
          : <div/>
      }
      {
        this.state.isWriteSuccess
          ? <div>
              <h1>HASH IS ON THE BLOCK CHAIN</h1>
              <button onClick={() => {
                  contractInstance.get({from: account}).then((data) => {
                    console.log(data);
                    this.setState({blockChainHash: data});
                  })
                }}>READ HASH ON BLOCKCHAIN:contractInstance.get()</button>
            </div>
          : <div/>
      }
      {
        this.state.blockChainHash
          ? <div>
              <h3>READ THE HASH ON BLOCKCHAIN:{this.state.blockChainHash}</h3>
            </div>
          : <div/>
      }
      {
        this.state.blockChainHash
          ? <div>
              <h2>BROWSER ACCESS:{"http://localhost:8080/ipfs/" + this.state.imgHash}</h2>
              <img alt="" style={{
                  width: 1600
                }} src={"http://localhost:8080/ipfs/" + this.state.imgHash}/>
            </div>
          : <img alt=""/>
      }
    </div>);
  }
}
export default App

我希望有人能成为我的救主,非常感谢。

I am trying to make a solution to store the file in IPFS , and then put the hash on the blockchain.
But when I try to upload the file to IPFS here comes the error message

Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'hash')

I am using react , ganache , node.js , ipfs-http-client
here's my app.js code

import React, {Component} from 'react'
import SimpleStorageContract from '../src/SimpleStorage.json'
import getWeb3 from './utils/getWeb3'
import './css/oswald.css'
import './css/open-sans.css'
import './css/pure-min.css'
import './App.css'
const ipfsAPI = require('ipfs-http-client');
const ipfs = ipfsAPI.create({host: 'localhost', port: '5001', protocol: 'http'});
const contract = require('truffle-contract')
const simpleStorage = contract(SimpleStorageContract)
let account;
// Declaring this for later so we can chain functions on SimpleStorage.
let contractInstance;
let saveImageOnIpfs = (reader) => {
  return new Promise(function(resolve, reject) {
    const buffer = Buffer.from(reader.result);
    ipfs.add(buffer).then((response) => {
      console.log(response)
      resolve(response[0].hash);
    }).catch((err) => {
      console.error(err)
      reject(err);
    })
  })
}


class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      blockChainHash: null,
      web3: null,
      address: null,
      imgHash: null,
      isWriteSuccess: false
    }
  }
  componentWillMount() {
    ipfs.swarm.peers(function(err, res) {
      if (err) {
        console.error(err);
      } else {
        // var numPeers = res.Peers === null ? 0 : res.Peers.length;
        // console.log("IPFS - connected to " + numPeers + " peers");
        console.log(res);
      }
    });
    getWeb3.then(results => {
      this.setState({web3: results.web3})
      // Instantiate contract once web3 provided.
      this.instantiateContract()
    }).catch(() => {
      console.log('Error finding web3.')
    })
  }
  instantiateContract = () => {
    simpleStorage.setProvider(this.state.web3.currentProvider);
    this.state.web3.eth.getAccounts((error, accounts) => {
      account = accounts[0];
      simpleStorage.at('0xe7D98C99d71438A072B020138dD75347792FA214').then((contract) => {
        console.log(contract.address);
        contractInstance = contract;
        this.setState({address: contractInstance.address});
        return;
      });
    })
  }
  render() {
    return (<div className="App">
      {
        this.state.address
          ? <h1>CONNECT THE CONTRACT ADDRESS:{this.state.address}</h1>
          : <div/>
      }
      <h2>UPLOAD TO IPFS:</h2>
      <div>
        <label id="file">CLICK TO UPLOAD THE FILE</label>
        <input type="file" ref="file" id="file" name="file" multiple="multiple"/>
      </div>
      <div>
        <button onClick={() => {
            var file = this.refs.file.files[0];
            var reader = new FileReader();
            // reader.readAsDataURL(file);
            reader.readAsArrayBuffer(file)
            reader.onloadend = function(e) {
              console.log(reader);
              saveImageOnIpfs(reader).then((hash) => {
                console.log(hash);
                this.setState({imgHash: hash})
              });
            }.bind(this);
          }}>UPLOAD TO IPFS AND RETURN THE HASH</button>
      </div>
      {
        this.state.imgHash
          ? <div>
              <h2>imgHash:{this.state.imgHash}</h2>
              <button onClick={() => {
                  contractInstance.set(this.state.imgHash, {from: account}).then(() => {
                    console.log('HASH HAS BEEN WRITE ON BLOCKCHAIN');
                    this.setState({isWriteSuccess: true});
                  })
                }}>PUT HASH ON BLOCKCHAIN:contractInstance.set(imgHash)</button>
            </div>
          : <div/>
      }
      {
        this.state.isWriteSuccess
          ? <div>
              <h1>HASH IS ON THE BLOCK CHAIN</h1>
              <button onClick={() => {
                  contractInstance.get({from: account}).then((data) => {
                    console.log(data);
                    this.setState({blockChainHash: data});
                  })
                }}>READ HASH ON BLOCKCHAIN:contractInstance.get()</button>
            </div>
          : <div/>
      }
      {
        this.state.blockChainHash
          ? <div>
              <h3>READ THE HASH ON BLOCKCHAIN:{this.state.blockChainHash}</h3>
            </div>
          : <div/>
      }
      {
        this.state.blockChainHash
          ? <div>
              <h2>BROWSER ACCESS:{"http://localhost:8080/ipfs/" + this.state.imgHash}</h2>
              <img alt="" style={{
                  width: 1600
                }} src={"http://localhost:8080/ipfs/" + this.state.imgHash}/>
            </div>
          : <img alt=""/>
      }
    </div>);
  }
}
export default App

i hope someone can be my savior , thank you really much.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

塔塔猫 2025-02-11 21:00:27

看来您假设响应将始终定义。请检查响应[0]查看响应是否有效。看起来onloadend是异步调用的。尝试onload以确保您同步传递信息。

let saveImageOnIpfs = (reader) => {
  return new Promise(function(resolve, reject) {
    const buffer = Buffer.from(reader.result);
    ipfs.add(buffer).then((response) => {
      console.log(response)
      if(response[0] !== undefined && response[0].hash !== undefined){
           resolve(response[0].hash);
      }else{
           console.log(response)
      }
    }).catch((err) => {
      console.error(err)
      reject(err);
    })
  })
}

It looks like you're assuming that the response will always be defined. Please check response[0] to see if the response is valid. It looks like onloadend is called asynchronously. Try onload to ensure you're passing information synchronously.

let saveImageOnIpfs = (reader) => {
  return new Promise(function(resolve, reject) {
    const buffer = Buffer.from(reader.result);
    ipfs.add(buffer).then((response) => {
      console.log(response)
      if(response[0] !== undefined && response[0].hash !== undefined){
           resolve(response[0].hash);
      }else{
           console.log(response)
      }
    }).catch((err) => {
      console.error(err)
      reject(err);
    })
  })
}
去了角落 2025-02-11 21:00:27

最后,我的答案得到了解决,

let saveImageOnIpfs= (reader) => {
  return new Promise(async(resolve, reject) => {
      try {
        const buffer = Buffer.from(reader.result);
          let results = await ipfs.add(buffer);
          let hash1 = results.path;
          resolve(hash1);
      } catch (err) {
          console.error(err);
          reject(err);
      }
  })
}

谢谢您的回答以帮助我。

At last , my answer has been solved

let saveImageOnIpfs= (reader) => {
  return new Promise(async(resolve, reject) => {
      try {
        const buffer = Buffer.from(reader.result);
          let results = await ipfs.add(buffer);
          let hash1 = results.path;
          resolve(hash1);
      } catch (err) {
          console.error(err);
          reject(err);
      }
  })
}

thank you for your answer to help me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文