【问题标题】:Ipfs node won't connect to my react app running on local hostipfs 节点不会连接到我在本地主机上运行的 react 应用程序
【发布时间】:2021-07-14 02:14:23
【问题描述】:

我正在尝试创建一个反应组件,让您提交 .jpeg 并上传 ipfs。守护进程启动,我可以在 ipfs-go-companion add on config 中查看 ipfs 节点

网关 - http://localhost:8080 API - http://127.0.0.1:5001

它有一个切换按钮,可以启用/禁用 localhost 的 ipfs 集成,但它被禁用,每次我按下它;它再次禁用自己。

在我的应用程序中,当我选择一个文件并单击提交按钮时,我收到以下错误。

fetch.browser.js:101 POST http://127.0.0.1:5001/api/v0/add?stream-channels=true&progress=false 403 (Forbidden)
fetchWith @ fetch.browser.js:101
fetch @ http.js:130
Client.fetch @ core.js:192
post @ http.js:174
addAll @ add-all.js:36
index.js:1 HTTPError: 403 - Forbidden

    at Object.errorHandler [as handleError] (http://localhost:3000/static/js/1.chunk.js:57836:15)
    at async Client.fetch (http://localhost:3000/static/js/1.chunk.js:61144:9)
    at async addAll (http://localhost:3000/static/js/1.chunk.js:54724:17)
    at async last (http://localhost:3000/static/js/1.chunk.js:67287:20)
    at async Object.add (http://localhost:3000/static/js/1.chunk.js:54865:14)
    at async handleSubmit (http://localhost:3000/static/js/main.chunk.js:1375:20)

我已经启动了 ipfs 守护进程

sudo ipfs daemon

我的文件上传组件是

import React, { Component, useEffect, useState } from "react";
import { Form, Col, Button, InputGroup } from 'react-bootstrap';
const ipfsClient = require('ipfs-http-client')
const Buffer = require('buffer').Buffer;

// connect to the default API address http://localhost:5001

const UploadImage = () => {

  const [request, setRequest] = useState({});
  const [file, setFile] = useState({});
  const [img, setImg] = useState('');

  const handleSubmit =  async (event) => {
    event.preventDefault();
  //  const { cid } = await ipfs.add(img)
    //const ipfs = ipfsClient('http://localhost:5001') // (the default in Node.js)
    const ipfs = ipfsClient('/ip4/127.0.0.1/tcp/5001')

    try {
      const file =  await ipfs.add(img)
    //  setFile(file)
       console.log(file)
     } catch (e) {
      console.error(e)
    }
  }

  const convertToBuffer = async(reader) => {
  //file is converted to a buffer for upload to IPFS
    const buffer = await Buffer.from(reader.result);
    setImg(buffer);
  };

  const captureFile = async(event) => {
    event.stopPropagation()
    event.preventDefault()
    const file = event.target.files[0];
    let reader = new window.FileReader();
    reader.onload = function(event) {
      //const re = convertToBuffer(res);
      const res = reader.readAsArrayBuffer(re);
            const re = convertToBuffer(res);

        console.log(img);
        //setImg(res)

    };
   // reader.readAsArrayBuffer(blob);
   // console.log(res);
       };

  const myChangeHandler = async(event) => {
    let nam = event.target.name;
    let val = event.target.value;
    switch (nam) {
      case 'img':
        console.log(img)
        setImg(val)
        break;
    }
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <div>
          <label for="profile_pic">Choose file to upload</label>
           <div style={{ padding: '10px' }}><p>Enter your name:</p>
            <input
              type="file"
              name='img'
              onChange={captureFile}
              accept=".jpg, .jpeg, .png"
              required
            /></div>

        </div>
        <div>
        <input type='submit' value="Submit" />
        </div>
      </form>
    </div>
  )
}

export default UploadImage;

当我运行守护程序时,我可以从终端和在http://127.0.0.1:5001/ 上运行的 IPFS GUI 添加文件,但每次单击提交按钮时都会收到 403 错误。在此之前我一直收到 Access-Control-Allow-Origin 错误,但我为 chrome 安装了此插件,现在我没有收到该错误

https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf

【问题讨论】:

    标签: html reactjs npm ipfs


    【解决方案1】:

    问题似乎在于 CORS 保留了 IPFS 节点上的默认设置:阻止所有连接。
    要解决此问题,您必须配置 CORS 标头。

    官方 IPFS 教程在这里:https://github.com/ipfs/ipfs-webui#configure-ipfs-api-cors-headers

    如果您想通过直接编辑配置文件或通过 WebUI 来执行此操作:

    API 部分的所有允许(可能不安全,请确保您位于防火墙后面)的示例节点配置是:

    "API": {
            "HTTPHeaders": {
                "Access-Control-Allow-Methods": [
                    "PUT",
                    "POST"
                ],
                "Access-Control-Allow-Origin": [
                    "*"
                ]
            }
        },
    

    将 allow-origin 设置为 * 只会允许所有来源,但您也可以使用来源域列表更安全。

    如果您访问 https://webui.ipfs.iohttps://dev.webui.ipfs.io,他们会给您类似的说明,告诉您如何更改节点的 CORS 设置以便它们可以运行。

    【讨论】:

      猜你喜欢
      • 2018-03-04
      • 1970-01-01
      • 1970-01-01
      • 2019-06-29
      • 2019-01-12
      • 2023-04-11
      • 2019-06-16
      • 2018-01-10
      • 2014-12-13
      相关资源
      最近更新 更多