1

这是我在 App.js 中的代码,它总是返回一个“未处理的拒绝类型错误,说 ipfs.add(...). then 不是一个函数。

import React, { Component } from 'react';
import './App.css';
var ipfsAPI = require('ipfs-http-client')
var ipfs = ipfsAPI({host: 'localhost', port: '5001', protocol:'http'})
class App extends Component {
  saveTestBlobOnIpfs = (blob) => {
    return new Promise(function(resolve, reject) {
        const descBuffer = Buffer.from(blob, 'utf-8');
        ipfs.add(descBuffer).then((response) => {
        console.log(response)
        resolve(response[0].hash);
      }).catch((err) => {
        console.error(err)
        reject(err);
      })
    })
  }

  render() {
    return (
      <div className="App">
        <h1>IPFS Pool</h1>
        <input
          ref = "ipfs"
          style = {{width: 200, height: 50}}/>
        <button
          onClick = {() => {
            console.log("Upload Data to IPFS");
            let content = this.refs.ipfs.value;
            console.log(content);
            this.saveTestBlobOnIpfs(content).then((hash) => {
              console.log("Hash of uploaded data: " + hash)
            });
          }}
          style = {{height: 50}}>Upload Data to IPFS</button>
      </div>
    );
  }
}

export default App;

我是否需要添加异步函数或其他东西,我对 js 相当陌生,所以任何帮助将不胜感激。我只是不知道如何更改 ipfs.add 以使我的代码正常工作。

4

1 回答 1

1

我也遵循了相同的教程并遇到了同样的问题。该ipfs.add函数不再接受调用函数。更多信息在这里:https ://blog.ipfs.io/2020-02-01-async-await-refactor/

解决方案是将您的saveTestBlobOnIpfs功能变成异步/等待功能。像这样:

saveTestBlobOnIpfs = async (event) => {
    event.preventDefault();
    console.log('The file will be Submitted!');
    let data = this.state.buffer;
    console.log('Submit this: ', data);
    if (data){
      try{
        const postResponse = await ipfs.add(data) 
        console.log("postResponse", postResponse);
      } catch(e){
        console.log("Error: ", e)
      }
    } else{
      alert("No files submitted. Please try again.");
      console.log('ERROR: No data to submit');
    }
  }
于 2020-09-27T09:22:21.407 回答